import { useState, useEffect } from "react";
import {
  Sparkles,
  Plus,
  Trash2,
  X,
  Check,
  Search,
  MessageSquare,
  Image as ImageIcon,
  Video,
  Zap,
  Settings2,
  Loader2,
} from "lucide-react";
import {
  useModelProviders,
  useCreateProvider,
  useUpdateProvider,
  useDeleteProvider,
  useModelDefaults,
  useSaveModelDefaults,
} from "../../hooks/useModelProviders";
import type { ModelProvider, ModelDefaults, CreateProviderPayload } from "../../lib/api/modelProviders";

type Capability = "text" | "image" | "video";
type Protocol = "openai" | "gemini" | "dashscope" | "seedance" | "kling";

const protocolOptions: { value: Protocol; label: string; capabilities: Capability[] }[] = [
  { value: "openai", label: "OpenAI 兼容", capabilities: ["text", "image"] },
  { value: "dashscope", label: "阿里云百炼 (DashScope)", capabilities: ["text", "image"] },
  { value: "gemini", label: "Google Gemini", capabilities: ["text", "image", "video"] },
  { value: "seedance", label: "字节跳动 Seedance", capabilities: ["video"] },
  { value: "kling", label: "快手可灵 Kling", capabilities: ["image", "video"] },
];

const capabilityConfig = {
  text: { label: "语言模型 (LLM)", icon: MessageSquare, color: "blue", description: "用于剧本解析、角色提取、分镜规划等文本生成任务" },
  image: { label: "图片模型", icon: ImageIcon, color: "green", description: "用于角色四视图、场景图、道具图等图片生成任务" },
  video: { label: "视频模型", icon: Video, color: "purple", description: "用于分镜视频生成、首尾帧插值等视频生成任务" },
};

const colorMap: Record<string, string> = {
  blue: "from-blue-500 to-blue-600",
  green: "from-green-500 to-green-600",
  purple: "from-purple-500 to-purple-600",
};
const bgColorMap: Record<string, string> = {
  blue: "bg-blue-500/10 text-blue-600",
  green: "bg-green-500/10 text-green-600",
  purple: "bg-purple-500/10 text-purple-600",
};

type EditingProvider = Omit<ModelProvider, "id"> & { id?: number };
const EMPTY_DEFAULTS: ModelDefaults = {};

export function ModelSettings() {
  const [activeCapability, setActiveCapability] = useState<Capability>("text");
  const [showAddModal, setShowAddModal] = useState(false);
  const [editingProvider, setEditingProvider] = useState<EditingProvider | null>(null);
  const [modelSearch, setModelSearch] = useState("");

  const { data: providers = [], isLoading: loadingProviders } = useModelProviders();
  const { data: defaults, isLoading: loadingDefaults } = useModelDefaults();
  const createProvider = useCreateProvider();
  const updateProvider = useUpdateProvider();
  const deleteProvider = useDeleteProvider();
  const saveDefaults = useSaveModelDefaults();

  const [localDefaults, setLocalDefaults] = useState<ModelDefaults>(EMPTY_DEFAULTS);

  useEffect(() => {
    if (!loadingDefaults && defaults) {
      setLocalDefaults(defaults);
    }
  }, [loadingDefaults, defaults]);

  const getProvidersByCapability = (cap: Capability) =>
    providers.filter((p) => p.capability === cap);

  const getCheckedModels = (cap: Capability) => {
    const result: { providerId: number; providerName: string; modelId: string; modelName: string }[] = [];
    providers
      .filter((p) => p.capability === cap)
      .forEach((p) => {
        (p.models ?? []).filter((m) => m.checked).forEach((m) => {
          result.push({ providerId: p.id, providerName: p.name, modelId: m.id, modelName: m.name });
        });
      });
    return result;
  };

  const handleToggleModel = async (provider: ModelProvider, modelId: string) => {
    const updated = {
      ...provider,
      models: provider.models.map((m) =>
        m.id === modelId ? { ...m, checked: !m.checked } : m
      ),
    };
    await updateProvider.mutateAsync({ id: provider.id, patch: updated });
  };

  const handleDeleteProvider = async (id: number) => {
    if (!confirm("确定要删除该供应商配置吗？")) return;
    await deleteProvider.mutateAsync(id);
  };

  const openAddProvider = (capability: Capability) => {
    const proto = protocolOptions.find((p) => p.capabilities.includes(capability));
    setEditingProvider({
      name: "",
      protocol: proto?.value || "openai",
      capability,
      baseUrl: "",
      apiKey: "",
      secretKey: "",
      models: [],
    });
    setShowAddModal(true);
  };

  const handleSaveProvider = async () => {
    if (!editingProvider || !editingProvider.name.trim()) return;
    const payload: CreateProviderPayload = {
      name: editingProvider.name,
      protocol: editingProvider.protocol,
      capability: editingProvider.capability as Capability,
      baseUrl: editingProvider.baseUrl,
      apiKey: editingProvider.apiKey,
      secretKey: editingProvider.secretKey || "",
      models: editingProvider.models,
    };
    if (editingProvider.id) {
      await updateProvider.mutateAsync({ id: editingProvider.id, patch: payload });
    } else {
      await createProvider.mutateAsync(payload);
    }
    setShowAddModal(false);
    setEditingProvider(null);
  };

  const handleSaveDefaults = async () => {
    await saveDefaults.mutateAsync(localDefaults);
  };

  if (loadingProviders) {
    return (
      <div className="h-full flex items-center justify-center">
        <Loader2 className="w-6 h-6 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="h-full overflow-auto bg-background">
      <div className="p-6">
        <div className="max-w-5xl mx-auto">
          {/* Header */}
          <div className="mb-8">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#5b5ff9] to-[#8b5ff9] flex items-center justify-center">
                <Settings2 className="w-4 h-4 text-white" />
              </div>
              <h1 className="text-2xl font-semibold text-foreground">模型配置</h1>
            </div>
            <p className="text-sm text-muted-foreground">
              配置 AI 模型供应商和默认模型，支持语言模型、图片模型和视频模型的独立配置
            </p>
          </div>

          {/* Default Model Selection */}
          <div className="rounded-xl border border-border bg-card p-5 mb-6">
            <h2 className="text-base font-semibold text-foreground mb-4 flex items-center gap-2">
              <Zap className="w-4 h-4 text-yellow-500" />
              默认模型
            </h2>
            <p className="text-xs text-muted-foreground mb-4">
              选择每种任务类型的默认模型，生成时可临时切换。仅显示已勾选的模型。
            </p>
            <div className="grid grid-cols-3 gap-4">
              {(["text", "image", "video"] as Capability[]).map((cap) => {
                const config = capabilityConfig[cap];
                const Icon = config.icon;
                const checked = getCheckedModels(cap);
                const current = localDefaults[cap];

                return (
                  <div key={cap} className="rounded-lg border border-border p-4">
                    <div className="flex items-center gap-2 mb-3">
                      <div className={`w-7 h-7 rounded-md flex items-center justify-center ${bgColorMap[config.color]}`}>
                        <Icon className="w-3.5 h-3.5" />
                      </div>
                      <span className="text-sm font-medium text-foreground">{config.label}</span>
                    </div>
                    <select
                      value={current ? `${current.providerId}:${current.modelId}` : ""}
                      onChange={(e) => {
                        if (!e.target.value) {
                          setLocalDefaults({ ...localDefaults, [cap]: null });
                        } else {
                          const [pid, mid] = e.target.value.split(":");
                          setLocalDefaults({ ...localDefaults, [cap]: { providerId: Number(pid), modelId: mid } });
                        }
                      }}
                      className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 cursor-pointer"
                    >
                      <option value="">未选择</option>
                      {checked.map((m) => (
                        <option key={`${m.providerId}:${m.modelId}`} value={`${m.providerId}:${m.modelId}`}>
                          {m.providerName} / {m.modelName}
                        </option>
                      ))}
                    </select>
                    {checked.length === 0 && (
                      <p className="text-xs text-muted-foreground mt-2">请先在下方勾选可用模型</p>
                    )}
                  </div>
                );
              })}
            </div>
            <div className="mt-4 flex justify-end">
              <button
                onClick={handleSaveDefaults}
                disabled={saveDefaults.isPending}
                className="px-4 py-2 rounded-lg bg-primary text-white text-sm hover:opacity-90 transition-opacity flex items-center gap-2 disabled:opacity-60"
              >
                {saveDefaults.isPending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Check className="w-3.5 h-3.5" />}
                保存默认模型
              </button>
            </div>
          </div>

          {/* Capability Tabs */}
          <div className="flex items-center gap-2 mb-6">
            {(["text", "image", "video"] as Capability[]).map((cap) => {
              const config = capabilityConfig[cap];
              const Icon = config.icon;
              const count = getProvidersByCapability(cap).length;
              return (
                <button
                  key={cap}
                  onClick={() => setActiveCapability(cap)}
                  className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm transition-all ${
                    activeCapability === cap
                      ? `bg-gradient-to-r ${colorMap[config.color]} text-white shadow-sm`
                      : "bg-card border border-border text-foreground hover:bg-muted"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {config.label}
                  <span className={`px-1.5 py-0.5 rounded text-xs ${
                    activeCapability === cap ? "bg-white/20" : "bg-muted text-muted-foreground"
                  }`}>
                    {count}
                  </span>
                </button>
              );
            })}
          </div>

          <div className="rounded-lg border border-border bg-muted/30 p-3 mb-4 flex items-start gap-2">
            <Sparkles className="w-4 h-4 text-primary mt-0.5 flex-shrink-0" />
            <span className="text-xs text-muted-foreground">
              {capabilityConfig[activeCapability].description}
            </span>
          </div>

          {/* Provider List */}
          <div className="space-y-4">
            {getProvidersByCapability(activeCapability).map((provider) => (
              <div key={provider.id} className="rounded-xl border border-border bg-card overflow-hidden">
                <div className="p-4 border-b border-border">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${bgColorMap[capabilityConfig[activeCapability].color]}`}>
                        <span className="text-xs font-bold">{provider.name[0]}</span>
                      </div>
                      <div>
                        <h3 className="text-sm font-semibold text-foreground">{provider.name}</h3>
                        <div className="flex items-center gap-2 mt-0.5">
                          <span className="px-1.5 py-0.5 rounded text-xs bg-muted text-muted-foreground">
                            {protocolOptions.find((p) => p.value === provider.protocol)?.label}
                          </span>
                          <span className="text-xs text-muted-foreground">
                            {(provider.models ?? []).filter((m) => m.checked).length}/{(provider.models ?? []).length} 模型已启用
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => { setEditingProvider({ ...provider }); setShowAddModal(true); }}
                        className="px-3 py-1.5 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors text-xs flex items-center gap-1"
                      >
                        <Settings2 className="w-3 h-3" />
                        配置
                      </button>
                      <button
                        onClick={() => handleDeleteProvider(provider.id)}
                        disabled={deleteProvider.isPending}
                        className="p-1.5 rounded-lg border border-border bg-card text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50"
                      >
                        <Trash2 className="w-3 h-3" />
                      </button>
                    </div>
                  </div>

                  <div className="mt-3 flex items-center gap-4">
                    <div className="flex items-center gap-2 flex-1">
                      <span className="text-xs text-muted-foreground w-16">Base URL:</span>
                      <span className="text-xs text-foreground font-mono truncate">{provider.baseUrl || "未配置"}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs text-muted-foreground">API Key:</span>
                      {provider.apiKey ? (
                        <span className="text-xs text-foreground font-mono">{provider.apiKey}</span>
                      ) : (
                        <span className="text-xs text-yellow-600">未配置</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Model List */}
                <div className="p-4">
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-xs text-muted-foreground font-medium">可用模型</span>
                    <div className="relative">
                      <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground" />
                      <input
                        type="text"
                        placeholder="搜索模型..."
                        value={modelSearch}
                        onChange={(e) => setModelSearch(e.target.value)}
                        className="pl-7 pr-3 py-1 rounded-md border border-border bg-background text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/20 w-48"
                      />
                    </div>
                  </div>
                  <div className="space-y-1">
                    {(provider.models ?? [])
                      .filter((m) => !modelSearch || m.name.toLowerCase().includes(modelSearch.toLowerCase()) || m.id.toLowerCase().includes(modelSearch.toLowerCase()))
                      .map((model) => {
                        const isDefault = localDefaults[provider.capability as Capability]?.providerId === provider.id &&
                          localDefaults[provider.capability as Capability]?.modelId === model.id;
                        return (
                          <button
                            key={model.id}
                            onClick={() => handleToggleModel(provider, model.id)}
                            className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-all text-left ${
                              model.checked ? "bg-accent border border-primary/30" : "border border-transparent hover:bg-muted"
                            }`}
                          >
                            <div className="flex items-center gap-3">
                              <div className={`w-4 h-4 rounded border-2 flex items-center justify-center flex-shrink-0 ${
                                model.checked ? "border-primary bg-primary" : "border-muted-foreground"
                              }`}>
                                {model.checked && <Check className="w-3 h-3 text-white" />}
                              </div>
                              <div>
                                <span className="text-sm text-foreground">{model.name}</span>
                                <span className="text-xs text-muted-foreground ml-2 font-mono">{model.id}</span>
                              </div>
                            </div>
                            {isDefault && (
                              <span className="px-2 py-0.5 rounded-full text-xs bg-primary/10 text-primary font-medium">
                                默认
                              </span>
                            )}
                          </button>
                        );
                      })}
                    {(provider.models ?? []).length === 0 && (
                      <p className="text-xs text-muted-foreground py-2 text-center">暂无模型，请编辑供应商添加</p>
                    )}
                  </div>
                </div>
              </div>
            ))}

            <button
              onClick={() => openAddProvider(activeCapability)}
              className="w-full py-4 rounded-xl border-2 border-dashed border-border bg-card hover:bg-muted transition-colors flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground"
            >
              <Plus className="w-4 h-4" />
              添加{capabilityConfig[activeCapability].label}供应商
            </button>
          </div>
        </div>
      </div>

      {/* Add/Edit Provider Modal */}
      {showAddModal && editingProvider && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-8">
          <div className="bg-card rounded-2xl border border-border p-6 max-w-lg w-full max-h-[85vh] overflow-auto">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-lg font-semibold text-foreground">
                {editingProvider.id ? "编辑供应商" : "添加供应商"}
              </h2>
              <button
                onClick={() => { setShowAddModal(false); setEditingProvider(null); }}
                className="p-2 hover:bg-muted rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-muted-foreground" />
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">供应商名称</label>
                <input
                  type="text"
                  value={editingProvider.name}
                  onChange={(e) => setEditingProvider({ ...editingProvider, name: e.target.value })}
                  placeholder="例如：通义千问、OpenAI、Gemini"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">协议</label>
                <select
                  value={editingProvider.protocol}
                  onChange={(e) => setEditingProvider({ ...editingProvider, protocol: e.target.value })}
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 cursor-pointer"
                >
                  {protocolOptions
                    .filter((p) => p.capabilities.includes(editingProvider.capability as Capability))
                    .map((p) => (
                      <option key={p.value} value={p.value}>{p.label}</option>
                    ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">Base URL</label>
                <input
                  type="text"
                  value={editingProvider.baseUrl}
                  onChange={(e) => setEditingProvider({ ...editingProvider, baseUrl: e.target.value })}
                  placeholder="https://api.example.com/v1"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 font-mono text-sm"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">API Key</label>
                <input
                  type="password"
                  value={editingProvider.apiKey}
                  onChange={(e) => setEditingProvider({ ...editingProvider, apiKey: e.target.value })}
                  placeholder="sk-xxxxxxxxxxxxxxxx（留空保持不变）"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 font-mono text-sm"
                />
              </div>

              {editingProvider.protocol === "kling" && (
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">Secret Key</label>
                  <input
                    type="password"
                    value={editingProvider.secretKey || ""}
                    onChange={(e) => setEditingProvider({ ...editingProvider, secretKey: e.target.value })}
                    placeholder="可灵 Secret Key"
                    className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 font-mono text-sm"
                  />
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">模型 ID（回车添加）</label>
                <input
                  type="text"
                  placeholder="输入模型 ID，例如 gpt-4o"
                  className="w-full px-3 py-2 rounded-lg border border-border bg-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 font-mono text-sm"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      const v = e.currentTarget.value.trim();
                      if (v) {
                        setEditingProvider({
                          ...editingProvider,
                          models: [...editingProvider.models, { id: v, name: v, checked: true }],
                        });
                        e.currentTarget.value = "";
                      }
                    }
                  }}
                />
              </div>

              {editingProvider.models.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">已添加的模型</label>
                  <div className="space-y-1 max-h-40 overflow-auto">
                    {editingProvider.models.map((m) => (
                      <div key={m.id} className="flex items-center justify-between px-3 py-1.5 rounded-lg bg-muted">
                        <span className="text-xs font-mono text-foreground">{m.name}</span>
                        <button
                          onClick={() => setEditingProvider({
                            ...editingProvider,
                            models: editingProvider.models.filter((em) => em.id !== m.id),
                          })}
                          className="p-1 rounded hover:bg-background transition-colors"
                        >
                          <X className="w-3 h-3 text-muted-foreground" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <div className="flex gap-3 mt-6 pt-6 border-t border-border">
              <button
                onClick={() => { setShowAddModal(false); setEditingProvider(null); }}
                className="flex-1 px-4 py-2.5 rounded-lg border border-border bg-card text-foreground hover:bg-muted transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleSaveProvider}
                disabled={!editingProvider.name.trim() || createProvider.isPending || updateProvider.isPending}
                className="flex-1 px-4 py-2.5 rounded-lg bg-gradient-to-r from-[#5b5ff9] to-[#8b5ff9] text-white hover:shadow-md transition-all flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {(createProvider.isPending || updateProvider.isPending) ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Check className="w-4 h-4" />
                )}
                保存
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
