import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Pencil, Trash2, Plus } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

interface Category {
  id: string;
  name: string;
  description: string | null;
  display_order: number;
  is_active: boolean;
  parent_id: string | null;
  created_at: string;
  updated_at: string;
}

interface Brand {
  id: string;
  name: string;
  is_active: boolean;
}

export function CategoriesManager() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [selectedBrands, setSelectedBrands] = useState<string[]>([]);
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    display_order: 0,
    parent_id: null as string | null,
  });

  useEffect(() => {
    fetchCategories();
    fetchBrands();
  }, []);

  const fetchCategories = async () => {
    try {
      const { data, error } = await supabase
        .from("categories")
        .select("*")
        .order("display_order", { ascending: true });

      if (error) throw error;
      setCategories(data || []);
    } catch (error: any) {
      toast.error("获取分类失败: " + error.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchBrands = async () => {
    try {
      const { data, error } = await supabase
        .from("brands")
        .select("id, name, is_active")
        .eq("is_active", true)
        .order("display_order", { ascending: true });

      if (error) throw error;
      setBrands(data || []);
    } catch (error: any) {
      toast.error("获取品牌失败: " + error.message);
    }
  };

  const fetchCategoryBrands = async (categoryId: string) => {
    try {
      const { data, error } = await supabase
        .from("category_brands")
        .select("brand_id")
        .eq("category_id", categoryId);

      if (error) throw error;
      return data?.map(cb => cb.brand_id) || [];
    } catch (error: any) {
      toast.error("获取分类品牌失败: " + error.message);
      return [];
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      let categoryId: string;

      if (editingCategory) {
        const { error } = await supabase
          .from("categories")
          .update({
            name: formData.name,
            description: formData.description,
            display_order: formData.display_order,
            parent_id: formData.parent_id,
          })
          .eq("id", editingCategory.id);

        if (error) throw error;
        categoryId = editingCategory.id;
      } else {
        const { data, error } = await supabase
          .from("categories")
          .insert({
            name: formData.name,
            description: formData.description,
            display_order: formData.display_order,
            parent_id: formData.parent_id,
          })
          .select()
          .single();

        if (error) throw error;
        categoryId = data.id;
      }

      // 更新品牌关联
      // 先删除现有关联
      await supabase
        .from("category_brands")
        .delete()
        .eq("category_id", categoryId);

      // 添加新的关联
      if (selectedBrands.length > 0) {
        const categoryBrands = selectedBrands.map(brandId => ({
          category_id: categoryId,
          brand_id: brandId,
        }));

        const { error: brandsError } = await supabase
          .from("category_brands")
          .insert(categoryBrands);

        if (brandsError) throw brandsError;
      }

      toast.success(editingCategory ? "分类更新成功" : "分类创建成功");
      setDialogOpen(false);
      resetForm();
      fetchCategories();
    } catch (error: any) {
      toast.error(editingCategory ? "更新分类失败" : "创建分类失败", {
        description: error.message,
      });
    }
  };

  const handleDeleteCategory = async (id: string) => {
    if (!confirm("确定要删除此分类吗？")) return;

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

      if (error) throw error;
      toast.success("分类删除成功");
      fetchCategories();
    } catch (error: any) {
      toast.error("删除分类失败: " + error.message);
    }
  };

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

      if (error) throw error;
      toast.success(`分类已${!category.is_active ? "启用" : "停用"}`);
      fetchCategories();
    } catch (error: any) {
      toast.error("更新分类状态失败: " + error.message);
    }
  };

  const resetForm = () => {
    setFormData({
      name: "",
      description: "",
      display_order: 0,
      parent_id: null,
    });
    setSelectedBrands([]);
    setEditingCategory(null);
  };

  const openEditDialog = async (category: Category) => {
    setEditingCategory(category);
    setFormData({
      name: category.name,
      description: category.description || "",
      display_order: category.display_order,
      parent_id: category.parent_id,
    });
    
    // 获取该分类关联的品牌
    const brandIds = await fetchCategoryBrands(category.id);
    setSelectedBrands(brandIds);
    
    setDialogOpen(true);
  };

  const openCreateDialog = () => {
    resetForm();
    setDialogOpen(true);
  };

  if (loading) {
    return <div className="flex justify-center p-8">加载中...</div>;
  }

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle>商品分类管理</CardTitle>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={openCreateDialog}>
              <Plus className="w-4 h-4 mr-2" />
              添加分类
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>
                {editingCategory ? "编辑分类" : "添加新分类"}
              </DialogTitle>
            </DialogHeader>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <Label htmlFor="name">分类名称 *</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) =>
                    setFormData({ ...formData, name: e.target.value })
                  }
                  required
                />
              </div>
              <div>
                <Label htmlFor="description">描述</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) =>
                    setFormData({ ...formData, description: e.target.value })
                  }
                  rows={3}
                />
              </div>
              <div>
                <Label htmlFor="parent_id">父级分类（留空则为一级分类）</Label>
                <Select
                  value={formData.parent_id || "none"}
                  onValueChange={(value) =>
                    setFormData({
                      ...formData,
                      parent_id: value === "none" ? null : value,
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择父级分类" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">无（一级分类）</SelectItem>
                    {categories
                      .filter((c) => !c.parent_id && c.id !== editingCategory?.id)
                      .map((category) => (
                        <SelectItem key={category.id} value={category.id}>
                          {category.name}
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="display_order">显示顺序</Label>
                <Input
                  id="display_order"
                  type="number"
                  value={formData.display_order}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      display_order: parseInt(e.target.value) || 0,
                    })
                  }
                />
              </div>
              <div>
                <Label>关联品牌</Label>
                <div className="border rounded-md p-4 max-h-48 overflow-y-auto space-y-3">
                  {brands.length === 0 ? (
                    <p className="text-sm text-muted-foreground">暂无可用品牌</p>
                  ) : (
                    brands.map((brand) => (
                      <div key={brand.id} className="flex items-center space-x-2">
                        <Checkbox
                          id={`brand-${brand.id}`}
                          checked={selectedBrands.includes(brand.id)}
                          onCheckedChange={(checked) => {
                            if (checked) {
                              setSelectedBrands([...selectedBrands, brand.id]);
                            } else {
                              setSelectedBrands(selectedBrands.filter(id => id !== brand.id));
                            }
                          }}
                        />
                        <Label
                          htmlFor={`brand-${brand.id}`}
                          className="text-sm font-normal cursor-pointer"
                        >
                          {brand.name}
                        </Label>
                      </div>
                    ))
                  )}
                </div>
              </div>
              <div className="flex justify-end gap-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setDialogOpen(false)}
                >
                  取消
                </Button>
                <Button type="submit">
                  {editingCategory ? "更新" : "创建"}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b">
                <th className="text-left p-4">分类名称</th>
                <th className="text-left p-4">描述</th>
                <th className="text-left p-4">显示顺序</th>
                <th className="text-left p-4">状态</th>
                <th className="text-right p-4">操作</th>
              </tr>
            </thead>
            <tbody>
              {categories
                .filter((c) => !c.parent_id)
                .map((category) => (
                  <>
                    <tr key={category.id} className="border-b bg-muted/20">
                      <td className="p-4 font-semibold">{category.name}</td>
                      <td className="p-4 text-muted-foreground">
                        {category.description || "-"}
                      </td>
                      <td className="p-4">{category.display_order}</td>
                      <td className="p-4">
                        <Switch
                          checked={category.is_active}
                          onCheckedChange={() => handleToggleStatus(category)}
                        />
                      </td>
                      <td className="p-4 text-right space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openEditDialog(category)}
                        >
                          <Pencil className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeleteCategory(category.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </td>
                    </tr>
                    {categories
                      .filter((c) => c.parent_id === category.id)
                      .map((subCategory) => (
                        <tr key={subCategory.id} className="border-b">
                          <td className="p-4 pl-12 font-medium">
                            <span className="text-muted-foreground mr-2">└</span>
                            {subCategory.name}
                          </td>
                          <td className="p-4 text-muted-foreground">
                            {subCategory.description || "-"}
                          </td>
                          <td className="p-4">{subCategory.display_order}</td>
                          <td className="p-4">
                            <Switch
                              checked={subCategory.is_active}
                              onCheckedChange={() => handleToggleStatus(subCategory)}
                            />
                          </td>
                          <td className="p-4 text-right space-x-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => openEditDialog(subCategory)}
                            >
                              <Pencil className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleDeleteCategory(subCategory.id)}
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </td>
                        </tr>
                      ))}
                  </>
                ))}
            </tbody>
          </table>
        </div>
      </CardContent>
    </Card>
  );
}
