import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Plus, Edit, Trash2, ArrowUpDown, Search } from "lucide-react";
import { subscribeToPageState, PageState } from "./AdminAIAssistant";
import { cn } from "@/lib/utils";

interface Product {
  id: string;
  name: string;
  description: string | null;
  price: number;
  stock_quantity: number;
  category: string | null;
  brand: string | null;
  image_url: string | null;
  images: string[] | null;
  is_active: boolean;
  is_recommended: boolean;
  is_hot: boolean;
  specifications: Record<string, string> | null;
  created_at: string;
  updated_at: string;
}

export const ProductsManager = () => {
  const navigate = useNavigate();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [brandFilter, setBrandFilter] = useState("all");
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [highlightIds, setHighlightIds] = useState<string[]>([]);
  const [sortConfig, setSortConfig] = useState<{ field: string; direction: 'asc' | 'desc' }>({ field: 'created_at', direction: 'desc' });
  const { toast } = useToast();

  // 订阅AI页面状态变化
  useEffect(() => {
    const unsubscribe = subscribeToPageState((state) => {
      if (state.tab !== 'products') return;
      
      console.log('ProductsManager received page state:', state);
      
      // 应用过滤条件
      if (state.filters) {
        if (state.filters.brand) setBrandFilter(state.filters.brand);
        if (state.filters.category) setCategoryFilter(state.filters.category);
      }
      
      // 应用搜索
      if (state.search !== undefined) {
        setSearchTerm(state.search);
      }
      
      // 应用排序
      if (state.sort) {
        setSortConfig(state.sort);
      }
      
      // 高亮特定数据
      if (state.highlightIds) {
        setHighlightIds(state.highlightIds);
        setTimeout(() => setHighlightIds([]), 5000);
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);

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

  const fetchProducts = async () => {
    try {
      const { data, error } = await supabase
        .from("products")
        .select("*")
        .order("created_at", { ascending: false });

      if (error) throw error;
      
      const products = (data || []).map(product => ({
        ...product,
        specifications: product.specifications as Record<string, string> | null
      }));
      
      setProducts(products);
    } catch (error) {
      console.error("Error fetching products:", error);
      toast({
        title: "错误",
        description: "获取商品列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteProduct = async (id: string) => {
    if (!confirm("确定要删除这个商品吗？")) return;

    try {
      const { error } = await supabase
        .from("products")
        .delete()
        .eq("id", id);

      if (error) throw error;
      toast({
        title: "成功",
        description: "商品删除成功",
      });
      fetchProducts();
    } catch (error) {
      console.error("Error deleting product:", error);
      toast({
        title: "错误",
        description: "删除商品失败",
        variant: "destructive",
      });
    }
  };

  const handleToggleStatus = async (product: Product) => {
    try {
      const { error } = await supabase
        .from("products")
        .update({ is_active: !product.is_active })
        .eq("id", product.id);

      if (error) throw error;
      toast({
        title: "成功",
        description: `商品已${!product.is_active ? "上架" : "下架"}`,
      });
      fetchProducts();
    } catch (error) {
      console.error("Error toggling product status:", error);
      toast({
        title: "错误",
        description: "更新商品状态失败",
        variant: "destructive",
      });
    }
  };

  const handleToggleRecommended = async (product: Product) => {
    try {
      const { error } = await supabase
        .from("products")
        .update({ is_recommended: !product.is_recommended })
        .eq("id", product.id);

      if (error) throw error;
      toast({
        title: "成功",
        description: `商品已${!product.is_recommended ? "设为推荐" : "取消推荐"}`,
      });
      fetchProducts();
    } catch (error) {
      console.error("Error toggling product recommendation:", error);
      toast({
        title: "错误",
        description: "推荐状态切换失败",
        variant: "destructive",
      });
    }
  };

  const handleToggleHot = async (product: Product) => {
    try {
      const { error } = await supabase
        .from("products")
        .update({ is_hot: !product.is_hot })
        .eq("id", product.id);

      if (error) throw error;
      toast({
        title: "成功",
        description: `商品已${!product.is_hot ? "设为热门" : "取消热门"}`,
      });
      fetchProducts();
    } catch (error) {
      console.error("Error toggling product hot status:", error);
      toast({
        title: "错误",
        description: "热门状态切换失败",
        variant: "destructive",
      });
    }
  };

  if (loading) {
    return <div className="flex items-center justify-center p-8">
      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
    </div>;
  }

  // 获取唯一品牌和分类列表
  const uniqueBrands = [...new Set(products.map(p => p.brand).filter(Boolean))];
  const uniqueCategories = [...new Set(products.map(p => p.category).filter(Boolean))];

  // 过滤和排序
  const filteredProducts = [...products]
    .filter(product => {
      const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        product.brand?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        product.category?.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesBrand = brandFilter === 'all' || product.brand === brandFilter;
      const matchesCategory = categoryFilter === 'all' || product.category === categoryFilter;
      return matchesSearch && matchesBrand && matchesCategory;
    })
    .sort((a, b) => {
      let aVal: any = a[sortConfig.field as keyof Product];
      let bVal: any = b[sortConfig.field as keyof Product];
      if (sortConfig.field === 'created_at') {
        aVal = new Date(aVal).getTime();
        bVal = new Date(bVal).getTime();
      }
      if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1;
      return 0;
    });

  const handleSort = (field: string) => {
    setSortConfig(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'desc' ? 'asc' : 'desc'
    }));
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-2 flex-wrap">
            <div className="relative w-64">
              <Search className="absolute left-3 top-1/2 transform -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>
            <Select value={brandFilter} onValueChange={setBrandFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="品牌" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部品牌</SelectItem>
                {uniqueBrands.map(brand => (
                  <SelectItem key={brand} value={brand!}>{brand}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger className="w-32">
                <SelectValue placeholder="分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部分类</SelectItem>
                {uniqueCategories.map(cat => (
                  <SelectItem key={cat} value={cat!}>{cat}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <Button onClick={() => navigate("/admin/products/new")}>
            <Plus className="w-4 h-4 mr-2" />
            添加商品
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('name')}
              >
                商品名称 {sortConfig.field === 'name' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead>品牌</TableHead>
              <TableHead>分类</TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('price')}
              >
                价格 {sortConfig.field === 'price' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead 
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => handleSort('stock_quantity')}
              >
                库存 {sortConfig.field === 'stock_quantity' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
              </TableHead>
              <TableHead>状态</TableHead>
              <TableHead>推荐</TableHead>
              <TableHead>热门</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredProducts.map((product) => (
              <TableRow 
                key={product.id}
                className={cn(
                  highlightIds.includes(product.id) && "bg-primary/10 animate-pulse"
                )}
              >
                <TableCell className="font-medium">{product.name}</TableCell>
                <TableCell>{product.brand || "-"}</TableCell>
                <TableCell>{product.category || "-"}</TableCell>
                <TableCell>¥{product.price}</TableCell>
                <TableCell>{product.stock_quantity}</TableCell>
                <TableCell>
                  <Badge variant={product.is_active ? "default" : "secondary"}>
                    {product.is_active ? "上架" : "下架"}
                  </Badge>
                </TableCell>
                <TableCell>
                  <Badge 
                    variant={product.is_recommended ? "default" : "outline"}
                    className="cursor-pointer"
                    onClick={() => handleToggleRecommended(product)}
                  >
                    {product.is_recommended ? "是" : "否"}
                  </Badge>
                </TableCell>
                <TableCell>
                  <Badge 
                    variant={product.is_hot ? "destructive" : "outline"}
                    className="cursor-pointer"
                    onClick={() => handleToggleHot(product)}
                  >
                    {product.is_hot ? "是" : "否"}
                  </Badge>
                </TableCell>
                <TableCell>
                  <div className="flex space-x-2">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => navigate(`/admin/products/${product.id}`)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleToggleStatus(product)}
                    >
                      <Badge variant={product.is_active ? "default" : "secondary"}>
                        {product.is_active ? "下架" : "上架"}
                      </Badge>
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDeleteProduct(product.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
};
