/**
 * 商品图片风格预设管理
 * - 所有人可读，仅管理员可写（RLS 已配置）
 * - 内置风格不可删除（is_builtin），仅可改名/改 prompt/启停/排序
 * - 自定义风格可完整 CRUD
 */
import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Palette, Plus, Save, Trash2, Lock } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";

interface StylePreset {
  id: string;
  key: string;
  label: string;
  description: string | null;
  prompt: string;
  enabled: boolean;
  sort_order: number;
  is_builtin: boolean;
  updated_at: string;
}

const EMPTY_NEW: Omit<StylePreset, "id" | "updated_at" | "is_builtin"> = {
  key: "",
  label: "",
  description: "",
  prompt: "",
  enabled: true,
  sort_order: 100,
};

export function ImageStylePresetsManager() {
  const { toast } = useToast();
  const [items, setItems] = useState<StylePreset[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingId, setSavingId] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [draft, setDraft] = useState(EMPTY_NEW);

  const load = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("ai_image_style_presets")
      .select("*")
      .order("sort_order");
    if (error) {
      toast({ title: "加载失败", description: error.message, variant: "destructive" });
    } else {
      setItems((data || []) as StylePreset[]);
    }
    setLoading(false);
  };

  useEffect(() => {
    void load();
  }, []);

  const update = (id: string, patch: Partial<StylePreset>) => {
    setItems((prev) => prev.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  };

  const save = async (item: StylePreset) => {
    if (!item.label.trim() || !item.prompt.trim()) {
      toast({ title: "保存失败", description: "名称与 Prompt 不能为空", variant: "destructive" });
      return;
    }
    setSavingId(item.id);
    const { error } = await supabase
      .from("ai_image_style_presets")
      .update({
        label: item.label.trim(),
        description: item.description?.trim() || null,
        prompt: item.prompt.trim(),
        enabled: item.enabled,
        sort_order: item.sort_order,
      })
      .eq("id", item.id);
    setSavingId(null);
    if (error) {
      toast({ title: "保存失败", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "已保存", description: `${item.label} 已更新` });
    }
  };

  const remove = async (item: StylePreset) => {
    const { error } = await supabase
      .from("ai_image_style_presets")
      .delete()
      .eq("id", item.id);
    if (error) {
      toast({ title: "删除失败", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "已删除", description: item.label });
      setItems((prev) => prev.filter((c) => c.id !== item.id));
    }
  };

  const create = async () => {
    const key = draft.key.trim();
    const label = draft.label.trim();
    const prompt = draft.prompt.trim();
    if (!key || !label || !prompt) {
      toast({
        title: "创建失败",
        description: "Key、名称、Prompt 必填",
        variant: "destructive",
      });
      return;
    }
    if (!/^[a-z0-9_]+$/.test(key)) {
      toast({
        title: "Key 格式错误",
        description: "只允许小写字母、数字、下划线",
        variant: "destructive",
      });
      return;
    }
    setCreating(true);
    const { error } = await supabase.from("ai_image_style_presets").insert({
      key,
      label,
      description: draft.description?.trim() || null,
      prompt,
      enabled: draft.enabled,
      sort_order: draft.sort_order,
      is_builtin: false,
    });
    setCreating(false);
    if (error) {
      toast({ title: "创建失败", description: error.message, variant: "destructive" });
      return;
    }
    toast({ title: "已创建", description: label });
    setDraft(EMPTY_NEW);
    void load();
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-start justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-md bg-primary/10">
              <Palette className="h-4 w-4 text-primary" />
            </div>
            <div>
              <CardTitle className="text-base">商品图片风格预设</CardTitle>
              <CardDescription className="text-xs">
                管理 AI 生成商品图时可选的风格选项，前端"AI 生成产品图"下拉自动同步
              </CardDescription>
            </div>
          </div>
          <Badge variant="outline" className="text-xs">{items.length} 个风格</Badge>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {loading ? (
          <div className="space-y-2">
            {[1, 2, 3].map((i) => <Skeleton key={i} className="h-24 w-full" />)}
          </div>
        ) : (
          <div className="space-y-3">
            {items.map((item) => (
              <div key={item.id} className="border rounded-lg p-3 space-y-3 bg-card">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-center gap-2 flex-wrap">
                    <Badge variant="outline" className="font-mono text-xs">{item.key}</Badge>
                    {item.is_builtin && (
                      <Badge variant="secondary" className="text-xs gap-1">
                        <Lock className="h-3 w-3" /> 内置
                      </Badge>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Label className="text-sm">启用</Label>
                    <Switch
                      checked={item.enabled}
                      onCheckedChange={(v) => update(item.id, { enabled: v })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div className="space-y-1.5">
                    <Label className="text-xs">显示名称</Label>
                    <Input
                      value={item.label}
                      onChange={(e) => update(item.id, { label: e.target.value })}
                    />
                  </div>
                  <div className="space-y-1.5 md:col-span-2">
                    <Label className="text-xs">简短描述</Label>
                    <Input
                      value={item.description ?? ""}
                      onChange={(e) => update(item.id, { description: e.target.value })}
                      placeholder="下拉菜单中显示的副标题"
                    />
                  </div>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs">Prompt 片段（英文，注入到生成提示词中）</Label>
                  <Textarea
                    value={item.prompt}
                    onChange={(e) => update(item.id, { prompt: e.target.value })}
                    rows={3}
                    className="font-mono text-xs"
                  />
                </div>

                <div className="flex items-center justify-between gap-2 pt-1 border-t">
                  <div className="flex items-center gap-2">
                    <Label className="text-xs text-muted-foreground">排序</Label>
                    <Input
                      type="number"
                      value={item.sort_order}
                      onChange={(e) => update(item.id, { sort_order: Number(e.target.value) || 0 })}
                      className="h-7 w-20 text-xs"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    {!item.is_builtin && (
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button size="sm" variant="ghost" className="text-destructive">
                            <Trash2 className="h-3.5 w-3.5 mr-1" /> 删除
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>删除风格「{item.label}」？</AlertDialogTitle>
                            <AlertDialogDescription>
                              该操作不可撤销，前端下拉菜单将不再显示该选项。
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>取消</AlertDialogCancel>
                            <AlertDialogAction onClick={() => remove(item)}>
                              确认删除
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    )}
                    <Button
                      size="sm"
                      onClick={() => save(item)}
                      disabled={savingId === item.id}
                    >
                      <Save className="h-3.5 w-3.5 mr-1" />
                      {savingId === item.id ? "保存中..." : "保存"}
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 新增 */}
        <div className="border border-dashed rounded-lg p-3 space-y-3 bg-muted/30">
          <div className="flex items-center gap-2">
            <Plus className="h-4 w-4 text-primary" />
            <span className="text-sm font-medium">新增自定义风格</span>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="space-y-1.5">
              <Label className="text-xs">Key（唯一标识）</Label>
              <Input
                value={draft.key}
                onChange={(e) => setDraft({ ...draft, key: e.target.value })}
                placeholder="如 cyber_neon"
                className="font-mono text-xs"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">显示名称</Label>
              <Input
                value={draft.label}
                onChange={(e) => setDraft({ ...draft, label: e.target.value })}
                placeholder="如 赛博霓虹"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">简短描述</Label>
              <Input
                value={draft.description ?? ""}
                onChange={(e) => setDraft({ ...draft, description: e.target.value })}
                placeholder="下拉副标题"
              />
            </div>
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs">Prompt 片段（英文）</Label>
            <Textarea
              value={draft.prompt}
              onChange={(e) => setDraft({ ...draft, prompt: e.target.value })}
              rows={3}
              placeholder="Cyberpunk neon-lit scene, vivid magenta and cyan rim lights..."
              className="font-mono text-xs"
            />
          </div>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Label className="text-xs text-muted-foreground">排序</Label>
              <Input
                type="number"
                value={draft.sort_order}
                onChange={(e) => setDraft({ ...draft, sort_order: Number(e.target.value) || 0 })}
                className="h-7 w-20 text-xs"
              />
            </div>
            <Button size="sm" onClick={create} disabled={creating}>
              <Plus className="h-3.5 w-3.5 mr-1" />
              {creating ? "创建中..." : "创建风格"}
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
