import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ShoppingCart, Heart, Share2, Star, Minus, Plus, Home, Play, Volume2, VolumeX } from "lucide-react";
import { useCart } from "@/contexts/CartContext";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { useState, useEffect, useRef } from "react";
import { PLACEHOLDER_PRODUCT_LARGE } from "@/utils/placeholderImage";
import { cn } from "@/lib/utils";
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";

interface ProductDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  productId: string | null;
  onBuyNow?: () => void;
}

export function ProductDetailDialog({ open, onOpenChange, productId, onBuyNow }: ProductDetailDialogProps) {
  const { addItem } = useCart();
  const { toast } = useToast();
  const [product, setProduct] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [selectedImage, setSelectedImage] = useState(0);
  const [carouselApi, setCarouselApi] = useState<any>(null);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const [isVideoMuted, setIsVideoMuted] = useState(true);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 从数据库获取产品详情
  useEffect(() => {
    if (!productId || !open) return;
    
    const fetchProduct = async () => {
      setLoading(true);
      try {
        const { data, error } = await supabase
          .from("products")
          .select("*")
          .eq("id", productId)
          .maybeSingle();
          
        if (error) throw error;
        setProduct(data);
        setSelectedImage(0);
      } catch (error) {
        console.error("Error fetching product:", error);
        toast({
          title: "错误",
          description: "获取商品详情失败",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    };
    
    fetchProduct();
  }, [productId, open, toast]);

  // 监听轮播图变化，同步缩略图选中状态
  useEffect(() => {
    if (!carouselApi) return;

    const onSelect = () => {
      setSelectedImage(carouselApi.selectedScrollSnap());
    };

    carouselApi.on("select", onSelect);
    return () => {
      carouselApi.off("select", onSelect);
    };
  }, [carouselApi]);

  // 有视频时自动播放
  useEffect(() => {
    if (!product || !open) return;
    
    const hasVideo = product.video_url;
    if (hasVideo && videoRef.current) {
      // 延迟一下确保视频元素已渲染
      const timer = setTimeout(() => {
        if (videoRef.current) {
          videoRef.current.play().then(() => {
            setIsVideoPlaying(true);
          }).catch(err => {
            console.log('Auto-play prevented:', err);
          });
        }
      }, 300);
      return () => clearTimeout(timer);
    }
  }, [product, open]);

  const handleAddToCart = () => {
    if (!product) return;
    
    for (let i = 0; i < quantity; i++) {
      addItem({
        id: product.id,
        name: product.name,
        price: product.price,
        image_url: product.image_url,
        category: product.category,
        stock_quantity: product.stock_quantity
      });
    }
    toast({
      title: "添加成功",
      description: `${product.name} x${quantity} 已加入购物车`
    });
  };

  const handleBuyNow = () => {
    handleAddToCart();
    onOpenChange(false);
    onBuyNow?.();
  };

  const decreaseQuantity = () => {
    if (quantity > 1) setQuantity(quantity - 1);
  };

  const increaseQuantity = () => {
    if (quantity < (product?.stock_quantity || 1)) setQuantity(quantity + 1);
  };

  // 获取商品图片和视频列表
  const productVideoUrl = product ? (product as any).video_url : null;
  const productImages = product 
    ? (product.images && product.images.length > 0 
        ? product.images 
        : [product.image_url || PLACEHOLDER_PRODUCT_LARGE])
    : [];
  
  // 如果有视频，将视频放在第一位
  const mediaItems: Array<{ type: 'video' | 'image'; url: string }> = [];
  if (productVideoUrl) {
    mediaItems.push({ type: 'video', url: productVideoUrl });
  }
  productImages.forEach(img => {
    mediaItems.push({ type: 'image', url: img });
  });

  const handleVideoToggle = () => {
    if (videoRef.current) {
      if (isVideoPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsVideoPlaying(!isVideoPlaying);
    }
  };

  const toggleVideoMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isVideoMuted;
      setIsVideoMuted(!isVideoMuted);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[1400px] w-[100vw] sm:w-[95vw] h-[100vh] sm:h-auto max-h-[100vh] sm:max-h-[95vh] p-0 overflow-hidden rounded-none sm:rounded-lg">
        {loading ? (
          <div className="flex items-center justify-center p-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-600"></div>
            <span className="ml-3 text-lg">加载中...</span>
          </div>
        ) : !product ? (
          <div className="p-12 text-center">
            <p className="text-muted-foreground text-lg">商品信息不存在</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-12 gap-0 h-full bg-background overflow-y-auto md:overflow-hidden">
            {/* 左侧缩略图 - 移动端隐藏 */}
            <div className="hidden md:block md:col-span-1 bg-muted/30 p-3 overflow-y-auto max-h-[95vh]">
              <div className="space-y-2">
                {mediaItems.map((item, idx) => (
                  <button
                    key={idx}
                    onClick={() => {
                      setSelectedImage(idx);
                      carouselApi?.scrollTo(idx);
                    }}
                    className={cn(
                      "w-full aspect-square rounded border-2 overflow-hidden hover:border-red-600 transition-all cursor-pointer relative",
                      selectedImage === idx ? "border-red-600 ring-2 ring-red-600 ring-offset-2" : "border-border"
                    )}
                  >
                    {item.type === 'video' ? (
                      <>
                        <video src={item.url} className="w-full h-full object-cover" muted />
                        <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                          <Play className="h-4 w-4 text-white fill-white" />
                        </div>
                      </>
                    ) : (
                      <img src={item.url} alt={`图片${idx + 1}`} className="w-full h-full object-cover" />
                    )}
                  </button>
                ))}
              </div>
            </div>

            {/* 中间大图展示 - 使用轮播 */}
            <div className="md:col-span-5 bg-card flex items-center justify-center p-3 sm:p-6 md:border-r">
              <div className="w-full h-full flex items-center justify-center">
                {mediaItems.length === 1 ? (
                  <div className="w-full aspect-square bg-muted/10 rounded-lg overflow-hidden relative">
                    {mediaItems[0].type === 'video' ? (
                      <>
                        <video 
                          ref={videoRef}
                          src={mediaItems[0].url}
                          className="w-full h-full object-contain bg-black"
                          muted={isVideoMuted}
                          loop
                          playsInline
                          onClick={handleVideoToggle}
                        />
                        <div className="absolute bottom-4 left-4 right-4 flex items-center justify-between">
                          <Button
                            variant="secondary"
                            size="sm"
                            className="bg-black/60 hover:bg-black/80 text-white"
                            onClick={handleVideoToggle}
                          >
                            <Play className={cn("h-4 w-4 mr-1", isVideoPlaying && "hidden")} />
                            {isVideoPlaying ? "暂停" : "播放"}
                          </Button>
                          <Button
                            variant="secondary"
                            size="icon"
                            className="bg-black/60 hover:bg-black/80 text-white h-8 w-8"
                            onClick={toggleVideoMute}
                          >
                            {isVideoMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
                          </Button>
                        </div>
                      </>
                    ) : (
                      <img 
                        src={mediaItems[0].url} 
                        alt={product.name}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          e.currentTarget.src = PLACEHOLDER_PRODUCT_LARGE;
                        }}
                      />
                    )}
                  </div>
                ) : (
                  <Carousel className="w-full" opts={{ loop: true }} setApi={setCarouselApi}>
                    <CarouselContent>
                      {mediaItems.map((item, idx) => (
                        <CarouselItem key={idx}>
                          <div className="aspect-square bg-muted/10 rounded-lg overflow-hidden relative">
                            {item.type === 'video' ? (
                              <>
                                <video 
                                  ref={selectedImage === idx ? videoRef : undefined}
                                  src={item.url}
                                  className="w-full h-full object-contain bg-black"
                                  muted={isVideoMuted}
                                  loop
                                  playsInline
                                  onClick={handleVideoToggle}
                                />
                                <div className="absolute bottom-4 left-4 right-4 flex items-center justify-between">
                                  <Button
                                    variant="secondary"
                                    size="sm"
                                    className="bg-black/60 hover:bg-black/80 text-white"
                                    onClick={handleVideoToggle}
                                  >
                                    <Play className={cn("h-4 w-4 mr-1", isVideoPlaying && "hidden")} />
                                    {isVideoPlaying ? "暂停" : "播放"}
                                  </Button>
                                  <Button
                                    variant="secondary"
                                    size="icon"
                                    className="bg-black/60 hover:bg-black/80 text-white h-8 w-8"
                                    onClick={toggleVideoMute}
                                  >
                                    {isVideoMuted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
                                  </Button>
                                </div>
                              </>
                            ) : (
                              <img 
                                src={item.url} 
                                alt={`${product.name} - 图 ${idx + 1}`}
                                className="w-full h-full object-cover"
                                onError={(e) => {
                                  e.currentTarget.src = PLACEHOLDER_PRODUCT_LARGE;
                                }}
                              />
                            )}
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>
                    <CarouselPrevious className="left-2" />
                    <CarouselNext className="right-2" />
                  </Carousel>
                )}
              </div>
            </div>

            {/* 右侧商品详情 */}
            <div className="md:col-span-6 p-4 sm:p-6 md:p-8 md:overflow-y-auto md:max-h-[95vh]">
              <div className="space-y-6">
                {/* 商品标题和标签 */}
                <div>
                  <div className="flex items-start gap-2 mb-2">
                    <Badge className="bg-primary hover:bg-primary-hover text-primary-foreground">自营</Badge>
                    {product.is_recommended && (
                      <Badge variant="outline" className="border-amber-500 text-amber-600">推荐</Badge>
                    )}
                  </div>
                  <h1 className="text-2xl font-medium leading-relaxed">{product.name}</h1>
                  {product.category && (
                    <p className="text-sm text-muted-foreground mt-2">分类：{product.category}</p>
                  )}
                </div>

                {/* 价格区域 - 京东风格 */}
                <div className="bg-muted/30 p-6 rounded-lg space-y-4">
                  <div className="flex items-baseline gap-2">
                    <span className="text-sm text-muted-foreground">价格</span>
                    <span className="text-4xl font-bold text-red-600">¥{product.price.toFixed(2)}</span>
                    <span className="text-sm text-muted-foreground line-through">¥{(product.price * 1.2).toFixed(2)}</span>
                  </div>
                  
                  {/* 优惠信息 */}
                  <div className="flex items-center gap-2 text-sm">
                    <Badge variant="outline" className="border-red-600 text-red-600">满减</Badge>
                    <span className="text-muted-foreground">最高减194元</span>
                  </div>
                </div>

                {/* 配送信息 */}
                <div className="space-y-3 text-sm">
                  <div className="flex gap-4">
                    <span className="text-muted-foreground min-w-[60px]">送至</span>
                    <span className="font-medium">23:10前下单，预计明天(10月29日) 送达</span>
                  </div>
                  <div className="flex gap-4">
                    <span className="text-muted-foreground min-w-[60px]">服务</span>
                    <div className="flex flex-wrap gap-2">
                      <Badge variant="secondary" className="text-xs">59元免邮运费</Badge>
                      <Badge variant="secondary" className="text-xs">可延迟支付</Badge>
                      <Badge variant="secondary" className="text-xs">7天价保</Badge>
                      <Badge variant="secondary" className="text-xs">一年质保</Badge>
                    </div>
                  </div>
                </div>

                {/* 库存信息 */}
                <div className="flex gap-4 text-sm">
                  <span className="text-muted-foreground min-w-[60px]">库存</span>
                  <span className={cn(
                    "font-medium",
                    product.stock_quantity > 0 ? "text-green-600" : "text-red-600"
                  )}>
                    {product.stock_quantity > 0 ? `有货 ${product.stock_quantity}件` : '暂时缺货'}
                  </span>
                </div>

                {/* 数量选择器 */}
                <div className="flex items-center gap-4">
                  <span className="text-sm text-muted-foreground min-w-[60px]">数量</span>
                  <div className="flex items-center border rounded">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={decreaseQuantity}
                      disabled={quantity <= 1}
                      className="h-10 w-10 rounded-none border-r"
                    >
                      <Minus className="h-4 w-4" />
                    </Button>
                    <span className="px-6 font-medium">{quantity}</span>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={increaseQuantity}
                      disabled={quantity >= product.stock_quantity}
                      className="h-10 w-10 rounded-none border-l"
                    >
                      <Plus className="h-4 w-4" />
                    </Button>
                  </div>
                  <span className="text-sm text-muted-foreground">
                    (库存{product.stock_quantity}件)
                  </span>
                </div>

                {/* 操作按钮 - 京东风格 */}
                <div className="flex gap-3 pt-4">
                  <Button 
                    onClick={handleAddToCart} 
                    size="lg"
                    variant="outline"
                    className="flex-1 h-14 text-base border-red-600 text-red-600 hover:bg-red-50 hover:text-red-700 hover:border-red-700"
                    disabled={product.stock_quantity <= 0}
                  >
                    <ShoppingCart className="w-5 h-5 mr-2" />
                    加入购物车
                  </Button>
                  <Button 
                    onClick={handleBuyNow}
                    size="lg"
                    className="flex-1 h-14 text-base bg-red-600 hover:bg-red-700"
                    disabled={product.stock_quantity <= 0}
                  >
                    立即购买
                  </Button>
                </div>

                {/* 辅助操作 */}
                <div className="flex gap-4 pt-2">
                  <Button variant="ghost" size="sm" className="flex-1">
                    <Heart className="w-4 h-4 mr-2" />
                    收藏
                  </Button>
                  <Button variant="ghost" size="sm" className="flex-1">
                    <Share2 className="w-4 h-4 mr-2" />
                    分享
                  </Button>
                </div>

                {/* 商品描述 */}
                {product.description && (
                  <div className="border-t pt-6 mt-6">
                    <h3 className="font-semibold mb-3 text-base">商品介绍</h3>
                    <p className="text-sm text-muted-foreground leading-relaxed">{product.description}</p>
                  </div>
                )}

                {/* 商品参数 */}
                <div className="border-t pt-6">
                  <h3 className="font-semibold mb-4 text-base">商品参数</h3>
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="flex justify-between p-3 bg-muted/20 rounded">
                      <span className="text-muted-foreground">商品ID</span>
                      <span className="font-medium">{product.id.slice(0, 8)}</span>
                    </div>
                    <div className="flex justify-between p-3 bg-muted/20 rounded">
                      <span className="text-muted-foreground">分类</span>
                      <span className="font-medium">{product.category || "未分类"}</span>
                    </div>
                    <div className="flex justify-between p-3 bg-muted/20 rounded">
                      <span className="text-muted-foreground">状态</span>
                      <Badge variant={product.is_active ? "default" : "secondary"} className="text-xs">
                        {product.is_active ? "在售" : "下架"}
                      </Badge>
                    </div>
                    <div className="flex justify-between p-3 bg-muted/20 rounded">
                      <span className="text-muted-foreground">上架时间</span>
                      <span className="font-medium text-xs">{new Date(product.created_at).toLocaleDateString()}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
