import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { Copy, Search } from "lucide-react";

interface Product {
  id: string;
  name: string;
  brand: string | null;
  category: string | null;
  specifications: Record<string, string> | null;
}

interface SpecificationCopyDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCopy: (specifications: Array<{ key: string; value: string }>) => void;
  currentProductId?: string | null;
}

export function SpecificationCopyDialog({
  open,
  onOpenChange,
  onCopy,
  currentProductId,
}: SpecificationCopyDialogProps) {
  const [products, setProducts] = useState<Product[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (open) {
      fetchProducts();
    }
  }, [open]);

  useEffect(() => {
    if (searchTerm.trim()) {
      const filtered = products.filter(
        (product) =>
          product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          product.brand?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          product.category?.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredProducts(filtered);
    } else {
      setFilteredProducts(products);
    }
  }, [searchTerm, products]);

  const fetchProducts = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from("products")
        .select("id, name, brand, category, specifications")
        .not("specifications", "is", null)
        .order("created_at", { ascending: false });

      if (error) throw error;

      // 过滤掉当前编辑的商品并转换类型
      const filteredData = (data || [])
        .filter((p) => p.id !== currentProductId)
        .map((p) => ({
          ...p,
          specifications: p.specifications as Record<string, string> | null,
        }));
      setProducts(filteredData);
      setFilteredProducts(filteredData);
    } catch (error) {
      console.error("Error fetching products:", error);
      toast({
        title: "错误",
        description: "获取商品列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCopySpecs = (product: Product) => {
    if (!product.specifications) return;

    const specsArray = Object.entries(product.specifications).map(
      ([key, value]) => ({ key, value })
    );

    onCopy(specsArray);
    toast({
      title: "成功",
      description: `已从"${product.name}"复制 ${specsArray.length} 个规格`,
    });
    onOpenChange(false);
    setSearchTerm("");
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>从其他商品复制规格</DialogTitle>
          <DialogDescription>
            选择一个商品，将其规格复制到当前商品
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="搜索商品名称、品牌或分类..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>

          <ScrollArea className="h-[400px] pr-4">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
              </div>
            ) : filteredProducts.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                {searchTerm ? "未找到匹配的商品" : "暂无可复制的商品"}
              </div>
            ) : (
              <div className="space-y-2">
                {filteredProducts.map((product) => {
                  const specsCount = product.specifications
                    ? Object.keys(product.specifications).length
                    : 0;

                  return (
                    <div
                      key={product.id}
                      className="flex items-start justify-between p-4 border rounded-lg hover:bg-accent transition-colors"
                    >
                      <div className="flex-1 space-y-1">
                        <div className="font-medium">{product.name}</div>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          {product.brand && (
                            <Badge variant="outline">{product.brand}</Badge>
                          )}
                          {product.category && (
                            <Badge variant="outline">{product.category}</Badge>
                          )}
                          <span className="text-xs">
                            {specsCount} 个规格
                          </span>
                        </div>
                        {product.specifications && (
                          <div className="flex flex-wrap gap-1 mt-2">
                            {Object.keys(product.specifications)
                              .slice(0, 3)
                              .map((key) => (
                                <Badge
                                  key={key}
                                  variant="secondary"
                                  className="text-xs"
                                >
                                  {key}
                                </Badge>
                              ))}
                            {Object.keys(product.specifications).length > 3 && (
                              <Badge variant="secondary" className="text-xs">
                                +{Object.keys(product.specifications).length - 3}
                              </Badge>
                            )}
                          </div>
                        )}
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopySpecs(product)}
                        className="ml-4"
                      >
                        <Copy className="h-4 w-4 mr-2" />
                        复制
                      </Button>
                    </div>
                  );
                })}
              </div>
            )}
          </ScrollArea>
        </div>
      </DialogContent>
    </Dialog>
  );
}
