
import { useState, useEffect, useRef, useCallback } 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 { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Spinner } from "@/components/ui/spinner";
import { Separator } from "@/components/ui/separator";
import { useLlmProviders, updateLlmProviders, discoverProviderModels, testLlmModel } from '@/hooks/useApi';
import type { LlmProvidersConfig, LlmModel } from '@/types';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

export function AIConfigTab({
  newProviderBaseUrl,
  setNewProviderBaseUrl
}: {
  newProviderBaseUrl: string;
  setNewProviderBaseUrl: (url: string) => void;
}) {
  const { data: llmProviders, mutate: mutateLlmProviders } = useLlmProviders();
  
  const [localLlmProviders, setLocalLlmProviders] = useState<LlmProvidersConfig>({});
  const [isSavingLlm, setIsSavingLlm] = useState(false);
  const [llmSaveMessage, setLlmSaveMessage] = useState('');
  
  // New Provider Form State
  const [newProviderId, setNewProviderId] = useState('');
  // newProviderBaseUrl is passed as prop
  const [newProviderApiKey, setNewProviderApiKey] = useState('');

  // Provider Management State
  const [pendingApiKeys, setPendingApiKeys] = useState<Record<string, string>>({});
  const [editingApiKey, setEditingApiKey] = useState<Record<string, boolean>>({});
  const [discoverMessages, setDiscoverMessages] = useState<Record<string, string>>({});
  const [modelPickerOpen, setModelPickerOpen] = useState<Record<string, boolean>>({});
  const [candidateModels, setCandidateModels] = useState<Record<string, string[]>>({});
  const [modelSearch, setModelSearch] = useState<Record<string, string>>({});
  const [selectedCandidates, setSelectedCandidates] = useState<Record<string, Record<string, boolean>>>({});
  
  // New Model Input State
  const [newModelInputs, setNewModelInputs] = useState<Record<string, string>>({});
  const [newModelNameInputs, setNewModelNameInputs] = useState<Record<string, string>>({});
  const [newModelMenuOpen, setNewModelMenuOpen] = useState<Record<string, boolean>>({});
  const [newModelHighlightIndex, setNewModelHighlightIndex] = useState<Record<string, number>>({});

  // Test State
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [isTesting, setIsTesting] = useState<string | null>(null);

  // Refs for Auto-save
  const hasInitializedLlmRef = useRef(false);
  const autoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const savingStartedAtRef = useRef<number>(0);
  const llmDirtyRef = useRef(false);
  const latestServerPayloadRef = useRef<string>('');
  const lastSavedPayloadRef = useRef<string>('');

  const markLlmDirty = useCallback(() => {
    llmDirtyRef.current = true;
  }, []);

  const normalizeProviders = useCallback((obj: LlmProvidersConfig) => {
    const cloned: LlmProvidersConfig = JSON.parse(JSON.stringify(obj || {}));
    Object.keys(cloned).forEach(pid => {
      if (!cloned[pid].name || cloned[pid].name.trim().length === 0) {
        cloned[pid].name = pid;
      }
    });
    return cloned;
  }, []);

  const buildMergedLlmPayload = useCallback(() => {
    const merged: LlmProvidersConfig = normalizeProviders(localLlmProviders || {});
    // 待更新的 API Key 覆盖
    Object.entries(pendingApiKeys || {}).forEach(([pid, key]) => {
      if (merged[pid]) merged[pid].api_key = key;
    });
    return merged;
  }, [localLlmProviders, pendingApiKeys, normalizeProviders]);

  const flushSaveLlmImmediate = useCallback(async () => {
    const payload = buildMergedLlmPayload();
    const payloadStr = JSON.stringify(payload);
    if (payloadStr === latestServerPayloadRef.current || payloadStr === lastSavedPayloadRef.current) {
      return;
    }
    savingStartedAtRef.current = Date.now();
    setIsSavingLlm(true);
    setLlmSaveMessage('自动保存中...');
    try {
      const updated = await updateLlmProviders(payload);
      await mutateLlmProviders(updated, false);
      lastSavedPayloadRef.current = payloadStr;
      llmDirtyRef.current = false;
      setPendingApiKeys({});
      setEditingApiKey({});
      setLlmSaveMessage('已自动保存');
    } catch (e: any) {
      setLlmSaveMessage(`保存失败: ${e?.message || '未知错误'}`);
    } finally {
      const elapsed = Date.now() - (savingStartedAtRef.current || 0);
      const minMs = 1000;
      const waitMs = elapsed >= minMs ? 0 : (minMs - elapsed);
      if (waitMs > 0) {
        await new Promise((resolve) => setTimeout(resolve, waitMs));
      }
      setIsSavingLlm(false);
      setTimeout(() => setLlmSaveMessage(''), 3000);
    }
  }, [buildMergedLlmPayload, mutateLlmProviders, setPendingApiKeys, setEditingApiKey]);

  // Initialize from Server Data
  useEffect(() => {
    if (llmProviders) {
      setLocalLlmProviders(llmProviders);
      const normalized = normalizeProviders(llmProviders);
      latestServerPayloadRef.current = JSON.stringify(normalized);
      llmDirtyRef.current = false;
    }
  }, [llmProviders, normalizeProviders]);

  // Auto-save Effect
  useEffect(() => {
    if (!hasInitializedLlmRef.current) {
      hasInitializedLlmRef.current = true;
      return;
    }
    if (!llmDirtyRef.current) {
      return;
    }
    if (autoSaveTimerRef.current) {
      clearTimeout(autoSaveTimerRef.current);
    }
    autoSaveTimerRef.current = setTimeout(() => {
      void flushSaveLlmImmediate();
    }, 500);
    return () => {
      if (autoSaveTimerRef.current) {
        clearTimeout(autoSaveTimerRef.current);
      }
    };
  }, [localLlmProviders, pendingApiKeys, flushSaveLlmImmediate]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle>AI Provider 管理</CardTitle>
          <div className="flex items-center gap-2 h-5">
            {isSavingLlm && (
              <>
                <Spinner className="text-gray-600" />
                <span className="text-xs text-muted-foreground">自动保存中...</span>
              </>
            )}
            {!isSavingLlm && llmSaveMessage && (
              <span className={`text-xs ${llmSaveMessage.includes('失败') ? 'text-red-600' : 'text-green-600'}`}>
                {llmSaveMessage}
              </span>
            )}
          </div>
        </div>
        <CardDescription>管理多个 Provider（API Key、Base URL）及其模型清单</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 新增 Provider */}
        <div className="space-y-3 p-4 border rounded-lg">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="space-y-2">
              <Label htmlFor="provider-id">Provider ID</Label>
              <Input id="provider-id" value={newProviderId} onChange={(e) => setNewProviderId(e.target.value)} placeholder="例如: openai_official" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="provider-baseurl">Base URL</Label>
              <Input id="provider-baseurl" value={newProviderBaseUrl} onChange={(e) => setNewProviderBaseUrl(e.target.value)} placeholder="例如: https://api.openai.com/v1" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="provider-apikey">API Key</Label>
              <Input id="provider-apikey" type="password" value={newProviderApiKey} onChange={(e) => setNewProviderApiKey(e.target.value)} placeholder="输入新Provider的API Key" />
            </div>
          </div>
          <div className="flex gap-2">
            <Button
              onClick={() => {
                if (!newProviderId || !newProviderBaseUrl || !newProviderApiKey) {
                  setLlmSaveMessage('请完整填写 Provider 信息');
                  setTimeout(() => setLlmSaveMessage(''), 5000);
                  return;
                }
                if (localLlmProviders[newProviderId]) {
                  setLlmSaveMessage('Provider ID 已存在');
                  setTimeout(() => setLlmSaveMessage(''), 5000);
                  return;
                }
                markLlmDirty();
                setLocalLlmProviders(prev => ({
                  ...prev,
                  [newProviderId]: {
                    name: newProviderId,
                    api_base_url: newProviderBaseUrl,
                    api_key: newProviderApiKey,
                    models: [],
                  },
                }));
                setNewProviderId('');
                setNewProviderBaseUrl('');
                setNewProviderApiKey('');
              }}
            >
              新增 Provider
            </Button>
          </div>
        </div>

        <Separator />

        {/* Provider 列表 */}
        <div className="space-y-6">
          {Object.entries(localLlmProviders || {}).map(([providerId, provider]) => {
            const message = discoverMessages[providerId];
            const candidates = candidateModels[providerId] || [];
            const query = (modelSearch[providerId] || '').trim().toLowerCase();
            const filteredCandidates = candidates.filter(id => id.toLowerCase().includes(query));
            const selectedMap = selectedCandidates[providerId] || {};
            return (
              <div key={providerId} className="space-y-4 p-4 border rounded-lg">
                <div className="flex items-center justify-between">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <h3 className="text-lg font-semibold">{providerId}</h3>
                      <Badge variant="secondary">Base on ID</Badge>
                      <span className="ml-2 inline-flex items-center justify-start w-24 h-5">
                        {isSavingLlm ? (
                          <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                            <Spinner className="text-gray-600" />
                            正在保存…
                          </span>
                        ) : null}
                      </span>
                    </div>
                    <div className="text-sm text-muted-foreground">{provider.api_base_url}</div>
                  </div>
                  <div className="flex gap-2">
                    <Button variant="outline" onClick={async () => {
                      try {
                        // 刷新前强制保存，确保后端使用最新配置
                        if (llmDirtyRef.current) {
                          await flushSaveLlmImmediate();
                        }
                        const resp = await discoverProviderModels(providerId);
                        const data = Array.isArray(resp?.data) ? resp.data : null;
                        if (!data) {
                          setDiscoverMessages(prev => ({ ...prev, [providerId]: '候选加载失败：不支持的响应结构' }));
                          setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
                          return;
                        }
                        const discovered: string[] = data
                          .map((x: any) => (typeof x?.id === 'string' ? x.id : null))
                          .filter((x: any) => typeof x === 'string');
                        setCandidateModels(prev => ({ ...prev, [providerId]: discovered }));
                        setDiscoverMessages(prev => ({ ...prev, [providerId]: `已加载候选模型 ${discovered.length} 个` }));
                        setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
                      } catch (e: any) {
                        setDiscoverMessages(prev => ({ ...prev, [providerId]: `加载失败：${e?.message || '未知错误'}` }));
                        setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
                      }
                    }}>刷新候选模型</Button>
                    <Button variant="outline" onClick={() => {
                      setModelPickerOpen(prev => ({ ...prev, [providerId]: !prev[providerId] }));
                    }}>{modelPickerOpen[providerId] ? '收起模型管理' : '管理模型'}</Button>
                    <Button
                      variant="destructive"
                      onClick={() => {
                        const next = { ...localLlmProviders };
                        delete next[providerId];
                        markLlmDirty();
                        setLocalLlmProviders(next);
                      }}
                    >
                      删除 Provider
                    </Button>
                  </div>
                </div>

                {message && (
                  <div className="text-sm">{message}</div>
                )}

                {modelPickerOpen[providerId] && (
                  <div className="space-y-3 p-3 border rounded-md bg-white/40">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3 items-end">
                      <div className="space-y-2">
                        <Label>搜索候选模型</Label>
                        <Input
                          value={modelSearch[providerId] || ''}
                          onChange={(e) => setModelSearch(prev => ({ ...prev, [providerId]: e.target.value }))}
                          placeholder="输入关键字过滤（前缀/包含均可）"
                        />
                      </div>
                      <div className="flex gap-2">
                        <Button variant="outline" onClick={() => {
                          const sel: Record<string, boolean> = { ...(selectedCandidates[providerId] || {}) };
                          filteredCandidates.forEach(id => { sel[id] = true; });
                          setSelectedCandidates(prev => ({ ...prev, [providerId]: sel }));
                        }}>全选筛选结果</Button>
                        <Button variant="outline" onClick={() => {
                          setSelectedCandidates(prev => ({ ...prev, [providerId]: {} }));
                        }}>清空选择</Button>
                      </div>
                      <div className="flex gap-2">
                        <Button onClick={() => {
                          const sel = selectedCandidates[providerId] || {};
                          const toAddIds = Object.keys(sel).filter(id => sel[id]);
                          if (toAddIds.length === 0) return;
                          markLlmDirty();
                          setLocalLlmProviders(prev => {
                            const existing = new Set((prev[providerId]?.models || []).map(m => m.model_id));
                            const toAdd: LlmModel[] = toAddIds
                              .filter(id => !existing.has(id))
                              .map(id => ({ model_id: id, name: null, is_active: true }));
                            return {
                              ...prev,
                              [providerId]: {
                                ...prev[providerId],
                                models: [...(prev[providerId]?.models || []), ...toAdd],
                              },
                            };
                          });
                          setSelectedCandidates(prev => ({ ...prev, [providerId]: {} }));
                        }}>添加选中模型</Button>
                      </div>
                    </div>
                    <ScrollArea className="border rounded-md" style={{ maxHeight: 280 }}>
                      <div className="p-2 space-y-1">
                        {filteredCandidates.length === 0 ? (
                          <div className="text-sm text-muted-foreground p-2">无匹配的候选模型</div>
                        ) : (
                          filteredCandidates.map(id => {
                            const checked = !!selectedMap[id];
                            return (
                              <div key={id} className="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
                                <div className="truncate text-sm">{id}</div>
                                <Checkbox
                                  checked={checked}
                                  onCheckedChange={(v) => {
                                    setSelectedCandidates(prev => {
                                      const cur = { ...(prev[providerId] || {}) };
                                      if (v) cur[id] = true; else delete cur[id];
                                      return { ...prev, [providerId]: cur };
                                    });
                                  }}
                                />
                              </div>
                            );
                          })
                        )}
                      </div>
                    </ScrollArea>
                  </div>
                )}

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label>Base URL</Label>
                    <Input
                      value={provider.api_base_url}
                      onChange={(e) => {
                        markLlmDirty();
                        setLocalLlmProviders(prev => ({
                          ...prev,
                          [providerId]: { ...prev[providerId], api_base_url: e.target.value },
                        }));
                      }}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>API Key</Label>
                    {!editingApiKey[providerId] ? (
                      <div className="flex items-center gap-2">
                        <Badge variant={provider.api_key ? 'default' : 'secondary'}>
                          {provider.api_key ? '已配置' : '未配置'}
                        </Badge>
                        <Button
                          variant="outline"
                          onClick={() => setEditingApiKey(prev => ({ ...prev, [providerId]: true }))}
                        >
                          更改 API Key
                        </Button>
                      </div>
                    ) : (
                      <div className="flex items-center gap-2">
                        <Input
                          type="password"
                          placeholder="输入新的 API Key"
                          value={pendingApiKeys[providerId] || ''}
                          onChange={(e) => {
                            markLlmDirty();
                            setPendingApiKeys(prev => ({ ...prev, [providerId]: e.target.value }));
                          }}
                        />
                        <Button
                          variant="outline"
                          onClick={() => setEditingApiKey(prev => ({ ...prev, [providerId]: false }))}
                        >
                          取消
                        </Button>
                      </div>
                    )}
                  </div>
                </div>

                <div className="space-y-2 pt-2">
                  <Label>模型列表</Label>
                  <div className="space-y-3">
                    {(provider.models || []).map((m) => (
                      <div key={m.model_id} className="grid grid-cols-1 md:grid-cols-3 gap-3 items-center">
                        <Input
                          value={m.model_id}
                          onChange={(e) => {
                            const v = e.target.value;
                            markLlmDirty();
                            setLocalLlmProviders(prev => ({
                              ...prev,
                              [providerId]: {
                                ...prev[providerId],
                                models: (prev[providerId].models || []).map(mm =>
                                  mm.model_id === m.model_id ? { ...mm, model_id: v } : mm
                                ),
                              },
                            }));
                          }}
                        />
                        <Input
                          value={m.name || ''}
                          onChange={(e) => {
                            const v = e.target.value;
                            markLlmDirty();
                            setLocalLlmProviders(prev => ({
                              ...prev,
                              [providerId]: {
                                ...prev[providerId],
                                models: (prev[providerId].models || []).map(mm =>
                                  mm.model_id === m.model_id ? { ...mm, name: v } : mm
                                ),
                              },
                            }));
                          }}
                          placeholder="可选别名"
                        />
                        <div className="flex items-center gap-3">
                          <div className="flex items-center gap-2">
                            <Checkbox
                              id={`${providerId}-${m.model_id}-active`}
                              checked={!!m.is_active}
                              onCheckedChange={(checked) => {
                                markLlmDirty();
                                setLocalLlmProviders(prev => ({
                                  ...prev,
                                  [providerId]: {
                                    ...prev[providerId],
                                    models: (prev[providerId].models || []).map(mm =>
                                      mm.model_id === m.model_id ? { ...mm, is_active: !!checked } : mm
                                    ),
                                  },
                                }));
                              }}
                            />
                            <label htmlFor={`${providerId}-${m.model_id}-active`} className="text-sm">启用</label>
                          </div>
                          <Button
                            variant="outline"
                            size="sm"
                            disabled={isTesting === m.model_id}
                            onClick={async () => {
                              setIsTesting(m.model_id);
                              try {
                                const res = await testLlmModel(provider.api_base_url, provider.api_key || pendingApiKeys[providerId] || '', m.model_id);
                                setTestResult({ success: true, message: typeof res === 'string' ? res : JSON.stringify(res, null, 2) });
                              } catch (e: any) {
                                setTestResult({ success: false, message: e.message || 'Test failed' });
                              } finally {
                                setIsTesting(null);
                              }
                            }}
                          >
                            {isTesting === m.model_id ? <Spinner className="h-3 w-3" /> : 'Test'}
                          </Button>
                          <Button
                            variant="destructive"
                            onClick={() => {
                              markLlmDirty();
                              setLocalLlmProviders(prev => ({
                                ...prev,
                                [providerId]: {
                                  ...prev[providerId],
                                  models: (prev[providerId].models || []).filter(mm => mm.model_id !== m.model_id),
                                },
                              }));
                            }}
                          >
                            删除
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div className="space-y-2">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3 items-start">
                      <div className="space-y-1 relative">
                        <Input
                          placeholder="新增模型 ID（可从候选中选择）"
                          value={newModelInputs[providerId] || ''}
                          onChange={(e) => {
                            const v = e.target.value;
                            setNewModelInputs(prev => ({ ...prev, [providerId]: v }));
                            setNewModelMenuOpen(prev => ({ ...prev, [providerId]: true }));
                            setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: 0 }));
                          }}
                          onFocus={() => {
                            setNewModelMenuOpen(prev => ({ ...prev, [providerId]: true }));
                          }}
                          onKeyDown={(e) => {
                            const typedRaw = (newModelInputs[providerId] || '');
                            const typed = typedRaw.trim().toLowerCase();
                            const existing = new Set((provider.models || []).map(m => m.model_id));
                            const list = (candidateModels[providerId] || [])
                              .filter(id => id.toLowerCase().includes(typed))
                              .filter(id => !existing.has(id))
                              .slice(0, 50);
                            const hi = newModelHighlightIndex[providerId] ?? 0;
                            if (e.key === 'ArrowDown') {
                              e.preventDefault();
                              if (list.length > 0) {
                                const next = Math.min(hi + 1, list.length - 1);
                                setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: next }));
                              }
                              return;
                            }
                            if (e.key === 'ArrowUp') {
                              e.preventDefault();
                              if (list.length > 0) {
                                const next = Math.max(hi - 1, 0);
                                setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: next }));
                              }
                              return;
                            }
                            if (e.key === 'Escape') {
                              setNewModelMenuOpen(prev => ({ ...prev, [providerId]: false }));
                              return;
                            }
                            if (e.key === 'Enter') {
                              const chosen = list.length > 0 && (newModelMenuOpen[providerId] ?? false) ? list[hi] : (newModelInputs[providerId] || '').trim();
                              const id = (chosen || '').trim();
                              if (!id) return;
                              const existsSet = new Set((provider.models || []).map(m => m.model_id));
                              if (existsSet.has(id)) return;
                              markLlmDirty();
                              setLocalLlmProviders(prev => ({
                                ...prev,
                                [providerId]: {
                                  ...prev[providerId],
                                  models: [
                                    ...(prev[providerId].models || []),
                                    { model_id: id, name: (newModelNameInputs[providerId] || '') || null, is_active: true },
                                  ],
                                },
                              }));
                              setNewModelInputs(prev => ({ ...prev, [providerId]: '' }));
                              setNewModelNameInputs(prev => ({ ...prev, [providerId]: '' }));
                              setNewModelMenuOpen(prev => ({ ...prev, [providerId]: false }));
                              setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: 0 }));
                            }
                          }}
                        />
                        {(() => {
                          const typed = (newModelInputs[providerId] || '').trim().toLowerCase();
                          const existing = new Set((provider.models || []).map(m => m.model_id));
                          const list = (candidateModels[providerId] || [])
                            .filter(id => id.toLowerCase().includes(typed))
                            .filter(id => !existing.has(id))
                            .slice(0, 50);
                          const open = !!newModelMenuOpen[providerId];
                          if (!typed || list.length === 0 || !open) return null;
                          const hi = newModelHighlightIndex[providerId] ?? 0;
                          return (
                            <div className="absolute z-10 mt-1 w-full border rounded-md bg-white shadow max-h-60 overflow-auto">
                              {list.map((id, idx) => (
                                <div
                                  key={id}
                                  className={`px-2 py-1 text-sm cursor-pointer ${hi === idx ? 'bg-gray-100' : 'hover:bg-gray-50'}`}
                                  onMouseEnter={() => {
                                    setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: idx }));
                                  }}
                                  onMouseDown={(ev) => {
                                    // 防止失焦导致菜单关闭
                                    ev.preventDefault();
                                  }}
                                  onClick={() => {
                                    setNewModelInputs(prev => ({ ...prev, [providerId]: id }));
                                  }}
                                >
                                  {id}
                                </div>
                              ))}
                            </div>
                          );
                        })()}
                      </div>
                      <Input
                        placeholder="模型别名（可选）"
                        value={newModelNameInputs[providerId] || ''}
                        onChange={(e) => {
                          const v = e.target.value;
                          setNewModelNameInputs(prev => ({ ...prev, [providerId]: v }));
                        }}
                      />
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          onClick={() => {
                            const id = (newModelInputs[providerId] || '').trim();
                            if (!id) return;
                            const exists = new Set((provider.models || []).map(m => m.model_id));
                            if (exists.has(id)) return;
                            const name = (newModelNameInputs[providerId] || '').trim();
                            markLlmDirty();
                            setLocalLlmProviders(prev => ({
                              ...prev,
                              [providerId]: {
                                ...prev[providerId],
                                models: [
                                  ...(prev[providerId].models || []),
                                  { model_id: id, name: name || null, is_active: true },
                                ],
                              },
                            }));
                            setNewModelInputs(prev => ({ ...prev, [providerId]: '' }));
                            setNewModelNameInputs(prev => ({ ...prev, [providerId]: '' }));
                            setNewModelMenuOpen(prev => ({ ...prev, [providerId]: false }));
                            setNewModelHighlightIndex(prev => ({ ...prev, [providerId]: 0 }));
                          }}
                        >
                          添加模型
                        </Button>
                      </div>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      若无候选，请先点击上方“刷新候选模型”加载后再输入筛选。
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </CardContent>

      <Dialog open={!!testResult} onOpenChange={(open) => !open && setTestResult(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{testResult?.success ? 'Test Successful' : 'Test Failed'}</DialogTitle>
            <DialogDescription>
              Response from model:
            </DialogDescription>
          </DialogHeader>
          <div className="max-h-[300px] overflow-auto p-4 bg-muted rounded-md whitespace-pre-wrap font-mono text-sm">
            {testResult?.message}
          </div>
          <DialogFooter>
            <Button onClick={() => setTestResult(null)}>Close</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
