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 { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Switch } from "@/components/ui/switch";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";

interface Brand {
  id: string;
  name: string;
  description: string | null;
  logo_url: string | null;
  display_order: number;
  is_active: boolean;
  aliases: string[] | null;
  created_at: string;
  updated_at: string;
}

export function BrandsManager() {
  const [brands, setBrands] = useState<Brand[]>([]);
  const [loading, setLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingBrand, setEditingBrand] = useState<Brand | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    logo_url: "",
    display_order: 0,
    aliases: "",
  });

  // 获取品牌列表
  const fetchBrands = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from("brands")
        .select("*")
        .order("display_order", { ascending: true });

      if (error) throw error;
      setBrands(data || []);
    } catch (error) {
      console.error("获取品牌列表失败:", error);
      toast.error("获取品牌列表失败");
    } finally {
      setLoading(false);
    }
  };

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

  // 提交表单（创建或更新）
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      toast.error("请输入品牌名称");
      return;
    }

    try {
      if (editingBrand) {
        // 更新品牌
        const { error } = await supabase
          .from("brands")
          .update({
            name: formData.name.trim(),
            description: formData.description.trim() || null,
            logo_url: formData.logo_url.trim() || null,
            display_order: formData.display_order,
            aliases: formData.aliases.trim() 
              ? formData.aliases.split(',').map(a => a.trim().toLowerCase()).filter(Boolean)
              : [],
          })
          .eq("id", editingBrand.id);

        if (error) throw error;
        toast.success("品牌更新成功");
      } else {
        // 创建品牌
        const { error } = await supabase.from("brands").insert({
          name: formData.name.trim(),
          description: formData.description.trim() || null,
          logo_url: formData.logo_url.trim() || null,
          display_order: formData.display_order,
          aliases: formData.aliases.trim()
            ? formData.aliases.split(',').map(a => a.trim().toLowerCase()).filter(Boolean)
            : [],
        });

        if (error) throw error;
        toast.success("品牌创建成功");
      }

      setIsDialogOpen(false);
      resetForm();
      fetchBrands();
    } catch (error) {
      console.error("保存品牌失败:", error);
      toast.error("保存品牌失败");
    }
  };

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

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

      if (error) throw error;
      toast.success("品牌删除成功");
      fetchBrands();
    } catch (error) {
      console.error("删除品牌失败:", error);
      toast.error("删除品牌失败");
    }
  };

  // 切换品牌状态
  const handleToggleStatus = async (id: string, currentStatus: boolean) => {
    try {
      const { error } = await supabase
        .from("brands")
        .update({ is_active: !currentStatus })
        .eq("id", id);

      if (error) throw error;
      toast.success("品牌状态更新成功");
      fetchBrands();
    } catch (error) {
      console.error("更新品牌状态失败:", error);
      toast.error("更新品牌状态失败");
    }
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: "",
      description: "",
      logo_url: "",
      display_order: 0,
      aliases: "",
    });
    setEditingBrand(null);
  };

  // 打开编辑对话框
  const openEditDialog = (brand: Brand) => {
    setEditingBrand(brand);
    setFormData({
      name: brand.name,
      description: brand.description || "",
      logo_url: brand.logo_url || "",
      display_order: brand.display_order,
      aliases: brand.aliases?.join(', ') || "",
    });
    setIsDialogOpen(true);
  };

  // 打开创建对话框
  const openCreateDialog = () => {
    resetForm();
    setIsDialogOpen(true);
  };

  if (loading) {
    return (
      <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>
    );
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <div>
            <CardTitle>品牌管理</CardTitle>
          </div>
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button onClick={openCreateDialog}>
                <Plus className="h-4 w-4 mr-2" />
                添加品牌
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>
                  {editingBrand ? "编辑品牌" : "添加品牌"}
                </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 })
                    }
                    placeholder="请输入品牌名称"
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="description">品牌描述</Label>
                  <Textarea
                    id="description"
                    value={formData.description}
                    onChange={(e) =>
                      setFormData({ ...formData, description: e.target.value })
                    }
                    placeholder="请输入品牌描述"
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="logo_url">Logo URL</Label>
                  <Input
                    id="logo_url"
                    value={formData.logo_url}
                    onChange={(e) =>
                      setFormData({ ...formData, logo_url: e.target.value })
                    }
                    placeholder="请输入品牌Logo URL"
                  />
                </div>

                <div>
                  <Label htmlFor="aliases">品牌别名</Label>
                  <Input
                    id="aliases"
                    value={formData.aliases}
                    onChange={(e) =>
                      setFormData({ ...formData, aliases: e.target.value })
                    }
                    placeholder="输入别名，用逗号分隔（如：redmi, hongmi）"
                  />
                  <p className="text-sm text-muted-foreground mt-1">
                    用于支持多语言搜索，如：红米的别名可以是 redmi, hongmi
                  </p>
                </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 className="flex justify-end space-x-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit">
                    {editingBrand ? "更新" : "创建"}
                  </Button>
                </div>
              </form>
            </DialogContent>
          </Dialog>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>品牌名称</TableHead>
                <TableHead>描述</TableHead>
                <TableHead>Logo</TableHead>
                <TableHead>显示顺序</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {brands.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground">
                    暂无品牌数据
                  </TableCell>
                </TableRow>
              ) : (
                brands.map((brand) => (
                  <TableRow key={brand.id}>
                    <TableCell className="font-medium">{brand.name}</TableCell>
                    <TableCell className="max-w-xs truncate">
                      {brand.description || "-"}
                    </TableCell>
                    <TableCell>
                      {brand.logo_url ? (
                        <img 
                          src={brand.logo_url} 
                          alt={brand.name}
                          className="h-8 w-8 object-contain"
                        />
                      ) : (
                        "-"
                      )}
                    </TableCell>
                    <TableCell>{brand.display_order}</TableCell>
                    <TableCell>
                      <Switch
                        checked={brand.is_active}
                        onCheckedChange={() =>
                          handleToggleStatus(brand.id, brand.is_active)
                        }
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex space-x-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => openEditDialog(brand)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteBrand(brand.id)}
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
