/**
 * AI 服务商配置中心（管理员）
 *
 * 路由：/admin/ai-providers
 * 数据源：ai_provider_configs 表（RLS：所有人可读，仅管理员可写）
 *
 * 功能：
 *  - 按分组（消费者/管理后台/部门 GenUI/部门洞察/系统能力/商品）展示所有 AI 配置
 *  - 切换服务商：lovable / qwen / volcengine / dify / coze / openai
 *  - 编辑模型名 / Endpoint / 引擎策略
 *  - 启用/停用单项配置
 */
import { useEffect, useState, useMemo } 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 { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import {
  Sparkles,
  Save,
  Info,
  ExternalLink,
  KeyRound,
  Users,
  ShieldCheck,
  LayoutDashboard,
  Lightbulb,
  Settings as SettingsIcon,
  Package,
} from "lucide-react";
import { AdminSubpageHeader } from "@/components/admin/AdminSubpageHeader";
import { ImageStylePresetsManager } from "@/components/admin/ai/ImageStylePresetsManager";

type Provider = "lovable" | "qwen" | "volcengine" | "dify" | "coze" | "openai";

interface ProviderConfig {
  id: string;
  purpose: string;
  provider: Provider;
  model: string;
  extra: Record<string, unknown>;
  enabled: boolean;
  description: string | null;
  category: string;
  display_order: number;
  updated_at: string;
}

const PURPOSE_LABELS: Record<string, string> = {
  default: "全局默认（兜底）",
  product_description: "商品描述生成",
  product_image: "商品图片生成",
  product_image_three_views: "商品三视图生成（图生图）",
  product_video: "商品视频生成（文生/图生视频）",
  consumer_chat: "消费者智能助理（C 端 /shop）",
  admin_chat: "管理后台 AI 助手",
  manager_genui: "店长工作台 GenUI",
  product_genui: "商品工作台 GenUI",
  marketing_genui: "营销工作台 GenUI",
  finance_genui: "财务工作台 GenUI",
  service_genui: "客服工作台 GenUI",
  manager_insights: "店长部门洞察",
  product_insights: "商品部门洞察",
  marketing_insights: "营销部门洞察",
  finance_insights: "财务部门洞察",
  service_insights: "客服部门洞察",
  system_audit: "系统审计",
  knowledge_embedding: "知识库向量嵌入",
};

const CATEGORY_META: Record<
  string,
  { label: string; icon: typeof Users; description: string }
> = {
  consumer: {
    label: "消费者端 (C 端)",
    icon: Users,
    description: "面向最终用户的智能助理与对话引擎",
  },
  admin: {
    label: "管理后台",
    icon: ShieldCheck,
    description: "店长 / 部门经理使用的 AI 助手与路由",
  },
  genui: {
    label: "部门工作台 GenUI",
    icon: LayoutDashboard,
    description: "5 个部门工作台的动态 UI 生成模型",
  },
  insights: {
    label: "部门主动洞察",
    icon: Lightbulb,
    description: "5 个部门的异常监控与商业洞察",
  },
  product: {
    label: "商品 AI 能力",
    icon: Package,
    description: "商品文案 / 图片生成",
  },
  system: {
    label: "系统能力",
    icon: SettingsIcon,
    description: "全局兜底、系统审计、知识库等",
  },
  general: {
    label: "其他",
    icon: SettingsIcon,
    description: "未分类配置",
  },
};

const PROVIDER_OPTIONS: { value: Provider; label: string; hint: string }[] = [
  { value: "lovable", label: "Lovable AI Gateway", hint: "无需配置，按调用计费（Gemini/GPT/Claude）" },
  { value: "dify", label: "Dify", hint: "需要 DIFY_API_KEY + DIFY_BASE_URL" },
  { value: "coze", label: "Coze (扣子)", hint: "需要 COZE_API_TOKEN + COZE_BOT_ID" },
  { value: "qwen", label: "阿里云千问 / 通义万相", hint: "需要 QWEN_API_KEY" },
  { value: "volcengine", label: "火山方舟 (豆包)", hint: "需要 ARK_API_KEY + endpoint_id" },
  { value: "openai", label: "OpenAI", hint: "需要 OPENAI_API_KEY，主要用于 embedding" },
];

const MODEL_SUGGESTIONS: Record<Provider, { text: string[]; image: string[] }> = {
  lovable: {
    text: ["google/gemini-2.5-flash", "google/gemini-2.5-pro", "google/gemini-2.5-flash-lite"],
    image: ["google/gemini-2.5-flash-image"],
  },
  qwen: {
    text: ["qwen-plus", "qwen-max", "qwen-turbo"],
    image: ["wanx-v1", "wanx2.1-t2i-turbo"],
  },
  volcengine: {
    text: ["填入文本 endpoint_id（ep-xxxxxxxx）"],
    image: ["填入图像 endpoint_id（ep-xxxxxxxx）"],
  },
  dify: {
    text: ["dify_with_coze_fallback", "dify", "dify_only"],
    image: [],
  },
  coze: {
    text: ["coze", "coze_with_dify_fallback", "admin_workflow"],
    image: [],
  },
  openai: {
    text: ["text-embedding-3-small", "text-embedding-3-large", "gpt-4o-mini"],
    image: [],
  },
};

const CATEGORY_ORDER = ["consumer", "admin", "genui", "insights", "product", "system", "general"];

export default function AIProvidersPage() {
  const { toast } = useToast();
  const [configs, setConfigs] = useState<ProviderConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingId, setSavingId] = useState<string | null>(null);

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

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

  const grouped = useMemo(() => {
    const map = new Map<string, ProviderConfig[]>();
    for (const c of configs) {
      const k = c.category || "general";
      if (!map.has(k)) map.set(k, []);
      map.get(k)!.push(c);
    }
    // 按预定义顺序输出
    return CATEGORY_ORDER
      .filter((cat) => map.has(cat))
      .map((cat) => ({ category: cat, items: map.get(cat)!.sort((a, b) => a.display_order - b.display_order) }));
  }, [configs]);

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

  const save = async (cfg: ProviderConfig) => {
    setSavingId(cfg.id);
    const { error } = await supabase
      .from("ai_provider_configs")
      .update({
        provider: cfg.provider,
        model: cfg.model.trim(),
        enabled: cfg.enabled,
      })
      .eq("id", cfg.id);
    setSavingId(null);
    if (error) {
      toast({ title: "保存失败", description: error.message, variant: "destructive" });
    } else {
      toast({
        title: "已保存",
        description: `${PURPOSE_LABELS[cfg.purpose] || cfg.purpose} 已更新`,
      });
    }
  };

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <AdminSubpageHeader
        title="AI 服务商配置"
        scope="ai-providers"
        fallback={{ path: "/admin/me", label: "我的" }}
      />
      <div className="container mx-auto p-6 max-w-5xl space-y-6">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-primary/10">
            <Sparkles className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">AI 引擎配置中心</h1>
            <p className="text-sm text-muted-foreground">
              统一管理系统所有 AI 模块使用的引擎与模型，配置即时生效
            </p>
          </div>
        </div>

      <Alert>
        <KeyRound className="h-4 w-4" />
        <AlertTitle>API Key 安全存储</AlertTitle>
        <AlertDescription className="space-y-1 text-sm">
          <p>本页只配置「用哪家服务商 + 哪个模型」，API Key 加密存储于 Supabase Secrets。</p>
          <p>所需 Secrets（已配置则无需再加）：</p>
          <ul className="list-disc pl-5 space-y-0.5">
            <li><code className="text-xs">LOVABLE_API_KEY</code> — Lovable AI（自动注入）</li>
            <li><code className="text-xs">DIFY_API_KEY</code> + <code className="text-xs">DIFY_BASE_URL</code> — Dify</li>
            <li><code className="text-xs">COZE_API_TOKEN</code> + <code className="text-xs">COZE_BOT_ID</code> — Coze</li>
            <li><code className="text-xs">QWEN_API_KEY</code> — 千问 / 通义万相</li>
            <li><code className="text-xs">ARK_API_KEY</code> + <code className="text-xs">ARK_ENDPOINT_TEXT/IMAGE</code> — 火山方舟</li>
            <li><code className="text-xs">OPENAI_API_KEY</code> — OpenAI（embedding）</li>
          </ul>
          <a
            href="https://supabase.com/dashboard/project/tlsofopqzrzuduinsicm/settings/functions"
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 text-primary hover:underline mt-1"
          >
            前往 Secrets 管理 <ExternalLink className="h-3 w-3" />
          </a>
        </AlertDescription>
      </Alert>

      {loading ? (
        <div className="space-y-4">
          {[1, 2, 3].map((i) => <Skeleton key={i} className="h-32 w-full" />)}
        </div>
      ) : (
        <Accordion type="multiple" defaultValue={["consumer", "admin"]} className="space-y-3">
          {grouped.map(({ category, items }) => {
            const meta = CATEGORY_META[category] || CATEGORY_META.general;
            const Icon = meta.icon;
            return (
              <AccordionItem
                key={category}
                value={category}
                className="border rounded-lg bg-card px-4"
              >
                <AccordionTrigger className="hover:no-underline">
                  <div className="flex items-center gap-3 text-left">
                    <div className="p-2 rounded-md bg-primary/10">
                      <Icon className="h-4 w-4 text-primary" />
                    </div>
                    <div>
                      <div className="font-semibold">{meta.label}</div>
                      <div className="text-xs text-muted-foreground font-normal">
                        {meta.description} · {items.length} 项
                      </div>
                    </div>
                  </div>
                </AccordionTrigger>
                <AccordionContent>
                  <div className="space-y-3 pt-2">
                    {items.map((cfg) => (
                      <ConfigCard
                        key={cfg.id}
                        cfg={cfg}
                        onUpdate={update}
                        onSave={save}
                        saving={savingId === cfg.id}
                      />
                    ))}
                    {category === "product" && <ImageStylePresetsManager />}
                  </div>
                </AccordionContent>
              </AccordionItem>
            );
          })}
        </Accordion>
      )}
      </div>
    </div>
  );
}

function ConfigCard({
  cfg,
  onUpdate,
  onSave,
  saving,
}: {
  cfg: ProviderConfig;
  onUpdate: (id: string, patch: Partial<ProviderConfig>) => void;
  onSave: (cfg: ProviderConfig) => void;
  saving: boolean;
}) {
  const isImage = cfg.purpose === "product_image";
  const suggestions =
    MODEL_SUGGESTIONS[cfg.provider]?.[isImage ? "image" : "text"] || [];
  const isChat = cfg.purpose === "consumer_chat" || cfg.purpose === "admin_chat";
  const modelLabel = isChat
    ? "策略 / 引擎模式"
    : cfg.provider === "volcengine"
    ? "Endpoint ID"
    : "模型";

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between gap-4">
          <div className="space-y-1">
            <CardTitle className="flex items-center gap-2 text-base">
              {PURPOSE_LABELS[cfg.purpose] || cfg.purpose}
              <Badge variant="outline" className="text-xs font-mono">
                {cfg.purpose}
              </Badge>
            </CardTitle>
            {cfg.description && (
              <CardDescription className="text-xs">{cfg.description}</CardDescription>
            )}
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <Label htmlFor={`enabled-${cfg.id}`} className="text-sm">
              启用
            </Label>
            <Switch
              id={`enabled-${cfg.id}`}
              checked={cfg.enabled}
              onCheckedChange={(v) => onUpdate(cfg.id, { enabled: v })}
            />
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div className="space-y-2">
            <Label>服务商</Label>
            <Select
              value={cfg.provider}
              onValueChange={(v) =>
                onUpdate(cfg.id, { provider: v as Provider, model: "" })
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {PROVIDER_OPTIONS.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    <div className="flex flex-col items-start">
                      <span>{opt.label}</span>
                      <span className="text-xs text-muted-foreground">
                        {opt.hint}
                      </span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>{modelLabel}</Label>
            <Input
              value={cfg.model}
              onChange={(e) => onUpdate(cfg.id, { model: e.target.value })}
              placeholder={suggestions[0] || "model name"}
            />
            {suggestions.length > 0 && (
              <div className="flex flex-wrap gap-1.5 pt-1">
                {suggestions.map((s) => (
                  <button
                    key={s}
                    type="button"
                    onClick={() => onUpdate(cfg.id, { model: s })}
                    className="text-xs px-2 py-0.5 rounded bg-muted hover:bg-muted/70 text-muted-foreground hover:text-foreground transition-colors font-mono"
                  >
                    {s}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {cfg.provider === "volcengine" && (
          <Alert variant="default" className="bg-muted/50 py-2">
            <Info className="h-4 w-4" />
            <AlertDescription className="text-xs">
              火山方舟需在「Endpoint ID」中填入推理接入点 ID（形如 <code>ep-2024xxxx</code>）。
            </AlertDescription>
          </Alert>
        )}

        {isChat && (
          <Alert variant="default" className="bg-muted/50 py-2">
            <Info className="h-4 w-4" />
            <AlertDescription className="text-xs">
              此项为聊天引擎策略。可选值：<code>dify</code>（仅 Dify）、<code>coze</code>（仅 Coze）、
              <code>dify_with_coze_fallback</code>（Dify 优先 + Coze 兜底）、
              <code>coze_with_dify_fallback</code>（Coze 优先 + Dify 兜底）。
            </AlertDescription>
          </Alert>
        )}

        <div className="flex items-center justify-between pt-2 border-t">
          <p className="text-xs text-muted-foreground">
            最后更新：{new Date(cfg.updated_at).toLocaleString("zh-CN")}
          </p>
          <Button
            onClick={() => onSave(cfg)}
            disabled={saving || !cfg.model.trim()}
            size="sm"
          >
            <Save className="h-4 w-4 mr-2" />
            {saving ? "保存中..." : "保存"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
