import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Upload, X, ImageIcon, Sparkles, Loader2, ChevronDown, Box } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { compressImage } from "@/utils/imageCompression";
import { supabase } from "@/integrations/supabase/client";
import { invokeEdge } from "@/lib/edgeClient";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

interface StylePreset {
  key: string;
  label: string;
  description: string | null;
}

const FALLBACK_STYLES: StylePreset[] = [
  { key: "studio_white", label: "纯白棚拍", description: "经典电商主图，白底居中" },
];

interface ProductImageUploadProps {
  images: string[];
  onChange: (images: string[]) => void;
  /** 商品名称，用于 AI 生成产品图 */
  productName?: string;
  /** 商品描述，用于 AI 生成产品图 */
  productDescription?: string;
}

export function ProductImageUpload({
  images,
  onChange,
  productName,
  productDescription,
}: ProductImageUploadProps) {
  const { toast } = useToast();
  const [uploading, setUploading] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [viewsLoadingIdx, setViewsLoadingIdx] = useState<number | null>(null);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [styles, setStyles] = useState<StylePreset[]>(FALLBACK_STYLES);

  useEffect(() => {
    let alive = true;
    (async () => {
      const { data, error } = await supabase
        .from("ai_image_style_presets")
        .select("key,label,description")
        .eq("enabled", true)
        .order("sort_order", { ascending: true });
      if (!alive) return;
      if (!error && data && data.length > 0) {
        setStyles(data as StylePreset[]);
      }
    })();
    return () => {
      alive = false;
    };
  }, []);

  const handleGenerateThreeViews = async (refUrl: string, idx: number) => {
    if (images.length >= 10) {
      toast({ title: "图片已达上限", description: "最多 10 张，请先删减", variant: "destructive" });
      return;
    }
    setViewsLoadingIdx(idx);
    try {
      const data = await invokeEdge<{
        views: Array<{ view: string; label: string; url: string }>;
        errors?: Array<{ label: string; error: string }>;
      }>("product-image-three-views", {
        body: {
          name: productName?.trim(),
          description: productDescription,
          referenceImage: refUrl,
        },
        timeoutMs: 120_000,
      });
      const newUrls = (data?.views ?? []).map((v) => v.url);
      if (newUrls.length === 0) throw new Error("未生成任何视图");
      const remaining = Math.max(0, 10 - images.length);
      const toAdd = newUrls.slice(0, remaining);
      onChange([...images, ...toAdd]);
      toast({
        title: "三视图生成成功",
        description: `已添加 ${toAdd.length} 张${data?.errors?.length ? `，${data.errors.length} 张失败` : ""}`,
      });
    } catch (err: any) {
      console.error(err);
      toast({
        title: "三视图生成失败",
        description: err?.message ?? "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setViewsLoadingIdx(null);
    }
  };

  const handleAIGenerate = async (style: string) => {
    const name = productName?.trim();
    if (!name) {
      toast({
        title: "请先填写商品名称",
        description: "AI 需要根据商品名称和描述生成图片",
        variant: "destructive",
      });
      return;
    }
    if (images.length >= 10) {
      toast({ title: "图片已达上限", description: "最多 10 张", variant: "destructive" });
      return;
    }
    setGenerating(true);
    try {
      const data = await invokeEdge<{ url: string }>("product-image-generate", {
        body: { name, description: productDescription, style },
        timeoutMs: 60_000,
      });
      if (data?.url) {
        onChange([...images, data.url]);
        const styleLabel = styles.find((s) => s.key === style)?.label ?? "默认风格";
        toast({ title: "AI 生成成功", description: `已添加 ${styleLabel} 商品图` });
      } else {
        throw new Error("未返回图片");
      }
    } catch (err: any) {
      console.error(err);
      toast({
        title: "AI 生成失败",
        description: err?.message ?? "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setGenerating(false);
    }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setUploading(true);
    const uploadedUrls: string[] = [];

    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        if (!file.type.startsWith("image/")) {
          toast({
            title: "错误",
            description: `文件 ${file.name} 不是图片格式`,
            variant: "destructive",
          });
          continue;
        }

        if (file.size > 5 * 1024 * 1024) {
          toast({
            title: "错误",
            description: `图片 ${file.name} 大小超过 5MB`,
            variant: "destructive",
          });
          continue;
        }

        let processedFile = file;
        if (file.type === "image/avif" || file.type === "image/webp" || file.size > 1024 * 1024) {
          processedFile = await compressImage(file, 1);
        }

        const fileExt = processedFile.name.split(".").pop();
        const fileName = `product_${Date.now()}_${i}.${fileExt}`;
        const filePath = `products/${fileName}`;

        const { error: uploadError } = await supabase.storage
          .from("product-images")
          .upload(filePath, processedFile);

        if (uploadError) throw uploadError;

        const { data } = supabase.storage.from("product-images").getPublicUrl(filePath);
        uploadedUrls.push(data.publicUrl);
      }

      if (uploadedUrls.length > 0) {
        onChange([...images, ...uploadedUrls]);
        toast({
          title: "成功",
          description: `成功上传 ${uploadedUrls.length} 张图片`,
        });
      }
    } catch (error) {
      console.error("Error uploading images:", error);
      toast({
        title: "错误",
        description: "图片上传失败，请重试",
        variant: "destructive",
      });
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const removeImage = (index: number) => {
    onChange(images.filter((_, i) => i !== index));
  };

  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    if (draggedIndex === null || draggedIndex === dropIndex) {
      setDraggedIndex(null);
      return;
    }

    const newImages = [...images];
    const draggedImage = newImages[draggedIndex];
    newImages.splice(draggedIndex, 1);
    newImages.splice(dropIndex, 0, draggedImage);
    onChange(newImages);
    setDraggedIndex(null);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2 flex-wrap">
        <Label className="text-sm font-medium">商品图片</Label>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                type="button"
                size="sm"
                variant="outline"
                disabled={generating || uploading || images.length >= 10}
                className="gap-1.5"
              >
                {generating ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : (
                  <Sparkles className="h-3.5 w-3.5 text-primary" />
                )}
                {generating ? "AI 生成中..." : "AI 生成产品图"}
                {!generating && <ChevronDown className="h-3.5 w-3.5 opacity-60" />}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-60">
              <DropdownMenuLabel>选择图片风格</DropdownMenuLabel>
              <DropdownMenuSeparator />
              {styles.map((s) => (
                <DropdownMenuItem
                  key={s.key}
                  onClick={() => handleAIGenerate(s.key)}
                  className="flex flex-col items-start gap-0.5 py-2"
                >
                  <span className="text-sm font-medium">{s.label}</span>
                  {s.description && (
                    <span className="text-xs text-muted-foreground">{s.description}</span>
                  )}
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <span className="text-xs text-muted-foreground">
            {images.length} / 10 张
          </span>
        </div>
      </div>
      
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
        {images.map((url, index) => (
          <div
            key={index}
            draggable
            onDragStart={() => handleDragStart(index)}
            onDragOver={handleDragOver}
            onDrop={(e) => handleDrop(e, index)}
            onDragEnd={() => setDraggedIndex(null)}
            className={cn(
              "group relative aspect-square rounded-xl overflow-hidden cursor-move transition-all duration-200",
              "border-2 hover:border-primary/50",
              draggedIndex === index ? "opacity-50 scale-95" : "opacity-100",
              index === 0 ? "border-primary ring-2 ring-primary/20" : "border-border"
            )}
          >
            <img
              src={url}
              alt={`商品图片 ${index + 1}`}
              className="w-full h-full object-cover"
            />
            {/* 封面标签 */}
            {index === 0 && (
              <div className="absolute top-2 left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded-md font-medium shadow-sm">
                封面
              </div>
            )}
            {/* 序号 */}
            {index > 0 && (
              <div className="absolute top-2 left-2 bg-background/80 backdrop-blur-sm text-foreground text-xs px-2 py-1 rounded-md font-medium">
                {index + 1}
              </div>
            )}
            {/* 操作按钮组 */}
            <div className="absolute top-2 right-2 flex flex-col gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
              <Button
                type="button"
                variant="secondary"
                size="icon"
                className="h-7 w-7 shadow-md"
                title="基于此图生成三视图"
                disabled={viewsLoadingIdx !== null || images.length >= 10}
                onClick={() => handleGenerateThreeViews(url, index)}
              >
                {viewsLoadingIdx === index ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Box className="h-4 w-4" />
                )}
              </Button>
              <Button
                variant="destructive"
                size="icon"
                className="h-7 w-7 shadow-md"
                onClick={() => removeImage(index)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
            {/* 悬浮遮罩 */}
            <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors pointer-events-none" />
            {/* 三视图生成中提示 */}
            {viewsLoadingIdx === index && (
              <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center gap-2 pointer-events-none">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
                <span className="text-xs font-medium">生成三视图中...</span>
              </div>
            )}
          </div>
        ))}
        
        {/* 上传按钮 */}
        {images.length < 10 && (
          <label className={cn(
            "aspect-square rounded-xl border-2 border-dashed flex flex-col items-center justify-center cursor-pointer transition-all duration-200",
            "border-muted-foreground/25 hover:border-primary hover:bg-primary/5",
            uploading && "pointer-events-none opacity-50"
          )}>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept="image/*"
              className="hidden"
              onChange={handleImageUpload}
              disabled={uploading}
            />
            {uploading ? (
              <div className="flex flex-col items-center gap-2">
                <div className="h-8 w-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                <span className="text-xs text-muted-foreground">上传中...</span>
              </div>
            ) : (
              <div className="flex flex-col items-center gap-2">
                <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
                  <Upload className="h-5 w-5 text-muted-foreground" />
                </div>
                <span className="text-xs text-muted-foreground font-medium">上传图片</span>
              </div>
            )}
          </label>
        )}
      </div>
      
      <p className="text-xs text-muted-foreground flex items-center gap-1">
        <ImageIcon className="h-3 w-3" />
        第一张为封面，拖动可调整顺序；悬停图片可生成三视图（正/侧/俯），支持 JPG、PNG、WebP
      </p>
    </div>
  );
}
