'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import type { ManagedModelConfigResponse, ManagedModelRecommendation, ManagedModelType } from '@/lib/model-config-types';
import { useCustomApiKeys } from '@/lib/custom-api-store';
import { Calendar, Check, Cpu, ExternalLink, Eye, EyeOff, Film, Globe, Image, Key, Loader2, MessageSquare, Plus, Settings, Shield, Sparkles, Trash2, Zap } from 'lucide-react';
type ProviderPreset = {
  id?: string;
  name: string;
  defaultUrl: string;
  defaultModel: string;
  defaultType: ManagedModelType;
  website?: string | null;
};

type ApiProviderGroup = {
  name: string;
  provider: string;
  keys: ReturnType<typeof useCustomApiKeys>['keys'];
};

// Fallback provider presets used before the server-managed config loads.
const PROVIDER_PRESETS: ProviderPreset[] = [
  { name: '硅基流动', defaultUrl: 'https://api.siliconflow.cn/v1/images/generations', defaultModel: 'black-forest-labs/FLUX.1-schnell', defaultType: 'image' as const, website: 'https://cloud.siliconflow.cn' },
  { name: 'New API', defaultUrl: 'https://your-newapi-domain.com/v1/images/generations', defaultModel: 'gpt-image-1', defaultType: 'image' as const, website: 'https://docs.newapi.pro' },
  { name: 'mozheAPI', defaultUrl: 'https://openai.mozhevip.top/v1/images/generations', defaultModel: '', defaultType: 'image' as const, website: 'https://openai.mozhevip.top' },
  { name: 'OpenAI', defaultUrl: 'https://api.openai.com/v1/images/generations', defaultModel: 'dall-e-3', defaultType: 'image' as const },
  { name: 'Stability AI', defaultUrl: 'https://api.stability.ai/v1/generation/stable-diffusion-xl/text-to-image', defaultModel: 'stable-diffusion-xl', defaultType: 'image' as const },
  { name: 'Midjourney', defaultUrl: '', defaultModel: 'midjourney-v6', defaultType: 'image' as const },
  { name: 'Runway', defaultUrl: 'https://api.runwayml.com/v1/image_to_video', defaultModel: 'gen-3-alpha', defaultType: 'video' as const },
  { name: 'Pika', defaultUrl: '', defaultModel: 'pika-1.0', defaultType: 'video' as const },
  { name: 'Kling', defaultUrl: '', defaultModel: 'kling-v1', defaultType: 'video' as const },
  { name: 'DeepSeek', defaultUrl: 'https://api.deepseek.com/v1/chat/completions', defaultModel: 'deepseek-chat', defaultType: 'text' as const },
  { name: 'OpenAI GPT', defaultUrl: 'https://api.openai.com/v1/chat/completions', defaultModel: 'gpt-4o', defaultType: 'text' as const },
  { name: '自定义', defaultUrl: '', defaultModel: '', defaultType: 'image' as const },
];

function getMozheApiUrl(providerName: string, type: ManagedModelType, model: string): string | null {
  if (providerName !== 'mozheAPI') return null;
  if (type === 'image' && model === 'gpt-image-2') {
    return 'https://openai.mozhevip.top/v1/images/generations';
  }
  if (type === 'text' && model === 'gpt-5.5') {
    return 'https://openai.mozhevip.top/v1/chat/completions';
  }
  return null;
}

export default function ApiKeyManager() {
  const { keys, add, update, remove, toggleActive } = useCustomApiKeys();
  const [showForm, setShowForm] = useState(false);
  const [showApiKey, setShowApiKey] = useState(false);

  // Form state
  const [provider, setProvider] = useState('');
  const [supplierName, setSupplierName] = useState('');
  const [apiUrl, setApiUrl] = useState('');
  const [modelName, setModelName] = useState('');
  const [modelNote, setModelNote] = useState('');
  const [apiKey, setApiKey] = useState('');
  const [formType, setFormType] = useState<'image' | 'video' | 'text'>('image');
  const [showModelSuggestions, setShowModelSuggestions] = useState(false);

  // Test connection state
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [testingKeyId, setTestingKeyId] = useState<string | null>(null);
  const [keyTestResults, setKeyTestResults] = useState<Record<string, { success: boolean; message: string }>>({});

  // Fetch models state
  const [fetchingModels, setFetchingModels] = useState(false);
  const [models, setModels] = useState<Array<{ id: string; name: string; description: string; provider: string }>>([]);
  const [fetchModelsError, setFetchModelsError] = useState<string | null>(null);
  const [managedProviders, setManagedProviders] = useState<ProviderPreset[]>([]);
  const [modelRecommendations, setModelRecommendations] = useState<ManagedModelRecommendation[]>([]);

  // Edit state
  const [editingKeyId, setEditingKeyId] = useState<string | null>(null);
  const providerOptions = managedProviders.length > 0 ? managedProviders : PROVIDER_PRESETS;
  const groupedKeys: ApiProviderGroup[] = Object.values(keys.reduce<Record<string, ApiProviderGroup>>((acc, key) => {
    const groupName = key.supplierName || key.provider || '未命名供应商';
    if (!acc[groupName]) {
      acc[groupName] = { name: groupName, provider: key.provider, keys: [] };
    }
    acc[groupName].keys.push(key);
    return acc;
  }, {}));
  const selectedProvider = providerOptions.find(p => p.name === provider);
  const modelSuggestions = modelRecommendations.filter(item =>
    item.type === formType && (!selectedProvider?.id || !item.providerId || item.providerId === selectedProvider.id)
  );
  const fallbackModelSuggestions = managedProviders.length > 0
    ? []
    : formType === 'image'
      ? [{ modelName: 'gpt-image-2', displayName: 'gpt-image-2' }]
      : [];
  const fetchedModelSuggestions = models.filter(
    model => model.id &&
      !modelSuggestions.some(suggestion => suggestion.modelName === model.id) &&
      !fallbackModelSuggestions.some(suggestion => suggestion.modelName === model.id)
  );
  const modelSuggestionOptions = [
    ...modelSuggestions.map(model => ({
      key: model.id,
      value: model.modelName,
      label: model.displayName || model.modelName,
    })),
    ...fallbackModelSuggestions.map(model => ({
      key: `fallback-${model.modelName}`,
      value: model.modelName,
      label: model.displayName,
    })),
    ...fetchedModelSuggestions.map(model => ({
      key: `fetched-${model.id}`,
      value: model.id,
      label: model.name || model.description || model.id,
    })),
  ].filter((option, index, all) => all.findIndex(item => item.value === option.value) === index);

  useEffect(() => {
    fetch('/api/model-config')
      .then(res => res.ok ? res.json() : null)
      .then((data: ManagedModelConfigResponse | null) => {
        if (!data) return;
        setManagedProviders((data.providers || []).map(p => ({
          id: p.id,
          name: p.name,
          defaultUrl: p.defaultApiUrl,
          defaultModel: p.defaultModel,
          defaultType: p.type,
          website: p.website,
        })));
        setModelRecommendations(data.recommendations || []);
      })
      .catch(() => {
        setManagedProviders([]);
        setModelRecommendations([]);
      });
  }, []);

  // Auto-fill URL and model when provider preset is selected
  const handleProviderChange = (value: string) => {
    setProvider(value);
    setSupplierName(value); // Set supplier name to provider name by default
    const preset = providerOptions.find(p => p.name === value);
    if (preset) {
      const nextType = preset.defaultType;
      const nextModel = preset.defaultModel;
      const mozheUrl = getMozheApiUrl(value, nextType, nextModel);
      if (mozheUrl) {
        setApiUrl(mozheUrl);
      } else if (value === 'mozheAPI') {
        // For mozheAPI, always set default URL to https://openai.mozhevip.top
        setApiUrl('https://openai.mozhevip.top');
      } else {
        setApiUrl(preset.defaultUrl);
      }
      setModelName(nextModel);
      if (nextType) setFormType(nextType);
    }
    setTestResult(null);
  };

  const handleModelTypeChange = (value: 'image' | 'video' | 'text') => {
    setFormType(value);
    const mozheUrl = getMozheApiUrl(provider, value, modelName);
    if (mozheUrl) setApiUrl(mozheUrl);
  };

  // Handle model name change for multimodal and image models
  const handleModelNameChange = (value: string) => {
    setModelName(value);
    const mozheUrl = getMozheApiUrl(provider, formType, value);
    if (mozheUrl) setApiUrl(mozheUrl);
  };

  const handleAddKey = () => {
    if (!provider.trim() || (!editingKeyId && !apiKey.trim())) return;
    if (editingKeyId) {
      // Update existing key
      update(editingKeyId, {
        provider: provider.trim(),
        supplierName: supplierName.trim() || provider.trim(),
        apiUrl: apiUrl.trim(),
        modelName: modelName.trim(),
        note: modelNote.trim(),
        apiKey: apiKey.trim(),
        type: formType,
        isActive: true,
      });
      setEditingKeyId(null);
    } else {
      // Add new key
      add({
        provider: provider.trim(),
        supplierName: supplierName.trim() || provider.trim(),
        apiUrl: apiUrl.trim(),
        modelName: modelName.trim(),
        note: modelNote.trim(),
        apiKey: apiKey.trim(),
        type: formType,
        isActive: true,
      });
    }
    setProvider('');
    setSupplierName('');
    setApiUrl('');
    setModelName('');
    setModelNote('');
    setApiKey('');
    setFormType('image');
    setShowForm(false);
    setShowApiKey(false);
    setTestResult(null);
  };

  const handleEditKey = (keyId: string) => {
    const key = keys.find(k => k.id === keyId);
    if (!key) return;
    setEditingKeyId(keyId);
    setProvider(key.provider);
    setSupplierName(key.supplierName || key.provider);
    setApiUrl(key.apiUrl);
    setModelName(key.modelName);
    setModelNote(key.note || '');
    setApiKey('');
    setFormType(key.type || 'image');
    setShowForm(false);
    setShowApiKey(false);
    setTestResult(null);
  };

  const handleAddModelForProvider = (group: ApiProviderGroup) => {
    const seed = group.keys[0];
    setEditingKeyId(null);
    setProvider(seed?.provider || group.provider || group.name);
    setSupplierName(group.name);
    setApiUrl(seed?.apiUrl || '');
    setModelName('');
    setModelNote('');
    setApiKey('');
    setFormType('image');
    setShowForm(true);
    setShowApiKey(false);
    setTestResult(null);
  };

  const handleTestConnection = async () => {
    if (!apiUrl.trim() || !apiKey.trim()) {
      setTestResult({ success: false, message: '请先填写 API 请求地址和 API Key' });
      return;
    }
    setTesting(true);
    setTestResult(null);
    try {
      const res = await fetch('/api/auth/test-api', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          apiUrl: apiUrl.trim(),
          apiKey: apiKey.trim(),
          modelName: modelName.trim(),
          provider: provider.trim(),
        }),
      });
      const data = await res.json();
      if (data.success) {
        setTestResult({ success: true, message: data.message });
      } else {
        const parts = [data.error];
        if (data.suggestion) parts.push(data.suggestion);
        setTestResult({ success: false, message: parts.join(' — ') });
      }
    } catch {
      setTestResult({ success: false, message: '测试请求发送失败，请检查网络' });
    } finally {
      setTesting(false);
    }
  };

  const handleFetchModels = async () => {
    if (!apiUrl.trim() || !apiKey.trim()) {
      setFetchModelsError('请先填写 API 请求地址和 API Key');
      return;
    }
    setFetchingModels(true);
    setFetchModelsError(null);
    setModels([]);
    try {
      const res = await fetch('/api/auth/fetch-models', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          apiUrl: apiUrl.trim(),
          apiKey: apiKey.trim(),
          provider: provider.trim(),
        }),
      });
      const data = await res.json();
      if (data.success) {
        setModels(data.models);
        setFetchModelsError(null);
      } else {
        const parts = [data.error];
        if (data.suggestion) parts.push(data.suggestion);
        setFetchModelsError(parts.join(' — '));
        setModels([]);
      }
    } catch {
      setFetchModelsError('获取模型列表失败，请检查网络');
      setModels([]);
    } finally {
      setFetchingModels(false);
    }
  };

  const resetForm = () => {
    setShowForm(false);
    setShowApiKey(false);
    setProvider('');
    setSupplierName('');
    setApiUrl('');
    setModelName('');
    setModelNote('');
    setApiKey('');
    setTestResult(null);
    setEditingKeyId(null);
  };

  const handleTestExistingKey = async (keyId: string) => {
    const key = keys.find(k => k.id === keyId);
    if (!key) return;
    if (!key.apiKey) {
      setKeyTestResults(prev => ({ ...prev, [keyId]: { success: false, message: '密钥已安全保存在服务端，请在编辑时输入新密钥后测试' } }));
      return;
    }
    setTestingKeyId(keyId);
    setKeyTestResults(prev => {
      const next = { ...prev };
      delete next[keyId];
      return next;
    });
    try {
      const res = await fetch('/api/auth/test-api', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          apiUrl: key.apiUrl,
          apiKey: key.apiKey,
          modelName: key.modelName,
          provider: key.provider,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setKeyTestResults(prev => ({ ...prev, [keyId]: { success: true, message: data.message } }));
      } else {
        const parts = [data.error];
        if (data.suggestion) parts.push(data.suggestion);
        setKeyTestResults(prev => ({ ...prev, [keyId]: { success: false, message: parts.join(' — ') } }));
      }
    } catch {
      setKeyTestResults(prev => ({ ...prev, [keyId]: { success: false, message: '测试请求发送失败' } }));
    } finally {
      setTestingKeyId(null);
    }
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><Key className="h-5 w-5" />API 管理</CardTitle>
          <CardDescription>配置第三方模型API，添加后可在创作中心直接选用</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Supported providers */}
          <div className="p-4 rounded-lg bg-muted/50 border border-border/50">
            <h3 className="font-medium mb-2">支持的模型供应商</h3>
            <div className="flex flex-wrap gap-2">
              {providerOptions.filter(p => p.name !== '自定义').map((p) => (
                <Badge key={p.name} variant="outline">{p.name}</Badge>
              ))}
              <Badge variant="outline" className="border-dashed">+ 自定义</Badge>
            </div>
            <p className="text-xs text-muted-foreground mt-2">
              添加密钥后，创作中心的模型列表会自动出现你配置的自定义模型
            </p>
          </div>

          {/* Recommended API Platform */}
          <div className="p-4 rounded-lg border border-primary/20 bg-primary/5">
            <div className="flex items-center gap-2 mb-2">
              <Sparkles className="h-4 w-4 text-primary" />
              <h3 className="font-medium">推荐 API 平台</h3>
            </div>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                  <img src="/icons/mozhe-api-logo.png" alt="mozheAPI" className="h-8 w-8 object-contain" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <span className="font-medium">mozheAPI</span>
                    <Badge variant="secondary" className="text-xs">推荐</Badge>
                  </div>
                  <p className="text-xs text-muted-foreground mt-0.5">兼容 OpenAI 格式的中转 API，生图模型开箱即用</p>
                </div>
              </div>
              <a
                href="https://openai.mozhevip.top"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1.5 text-sm text-primary hover:underline shrink-0 ml-4"
              >
                访问平台
                <ExternalLink className="h-3.5 w-3.5" />
              </a>
            </div>
          </div>

          <Separator />

          {/* Add key button / form */}
          {!showForm ? (
            <Button variant="outline" className="gap-2" onClick={() => setShowForm(true)}>
              <Plus className="h-4 w-4" />添加 API 密钥
            </Button>
          ) : (
            <div className="space-y-4 p-4 rounded-lg border border-primary/20 bg-primary/5">
              <h3 className="font-medium flex items-center gap-2">
                {editingKeyId ? (
                  <>
                    <Settings className="h-4 w-4 text-primary" />
                    编辑 API 密钥
                  </>
                ) : (
                  <>
                    <Plus className="h-4 w-4 text-primary" />
                    添加 API 密钥
                  </>
                )}
              </h3>

              {/* Row 1: Provider + Supplier Name */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Shield className="h-3.5 w-3.5 text-muted-foreground" />
                    供应商 <span className="text-destructive">*</span>
                  </Label>
                  <select
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                    value={provider}
                    onChange={(e) => handleProviderChange(e.target.value)}
                  >
                    <option value="">选择供应商...</option>
                    {providerOptions.map((p) => (
                      <option key={p.name} value={p.name}>{p.name}</option>
                    ))}
                  </select>
                </div>
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Shield className="h-3.5 w-3.5 text-muted-foreground" />
                    供应商名称
                  </Label>
                  <Input
                    placeholder="例如: 硅基流动, mozheAPI"
                    value={supplierName}
                    onChange={(e) => setSupplierName(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground">自定义供应商的名称，默认为选择的供应商</p>
                </div>
              </div>

              {/* Row 2: Model Type + Model Name */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Cpu className="h-3.5 w-3.5 text-muted-foreground" />
                    模型类型 <span className="text-destructive">*</span>
                  </Label>
                  <Select value={formType} onValueChange={v => handleModelTypeChange(v as 'image' | 'video' | 'text')}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="image">
                        <span className="flex items-center gap-2">
                          <Image className="h-3.5 w-3.5" />
                          生图模型
                        </span>
                      </SelectItem>
                      <SelectItem value="video">
                        <span className="flex items-center gap-2">
                          <Film className="h-3.5 w-3.5" />
                          视频模型
                        </span>
                      </SelectItem>
                      <SelectItem value="text">
                        <span className="flex items-center gap-2">
                          <MessageSquare className="h-3.5 w-3.5" />
                          多模态模型
                        </span>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">生图模型用于文生图/图生图，视频模型用于文生视频/图生视频，多模态模型用于图片反推提示词和提示词优化</p>
                </div>
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Cpu className="h-3.5 w-3.5 text-muted-foreground" />
                    模型名称
                  </Label>
                  <div className="relative">
                    <Input
                      placeholder={formType === 'image' ? '选择或输入生图模型' : formType === 'video' ? '选择或输入视频模型' : '选择或输入多模态模型'}
                      value={modelName}
                      onChange={(e) => {
                        handleModelNameChange(e.target.value);
                        setShowModelSuggestions(true);
                      }}
                      onClick={() => setShowModelSuggestions(true)}
                      onFocus={() => setShowModelSuggestions(true)}
                      onBlur={() => window.setTimeout(() => setShowModelSuggestions(false), 120)}
                    />
                    {showModelSuggestions && modelSuggestionOptions.length > 0 && (
                      <div className="absolute z-50 mt-1 max-h-56 w-full overflow-y-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md">
                        {modelSuggestionOptions.map((option) => (
                          <button
                            key={option.key}
                            type="button"
                            className="block w-full px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground"
                            onMouseDown={(e) => {
                              e.preventDefault();
                              handleModelNameChange(option.value);
                              setShowModelSuggestions(false);
                            }}
                          >
                            <span className="block font-medium">{option.value}</span>
                            {option.label !== option.value && (
                              <span className="block text-xs text-muted-foreground">{option.label}</span>
                            )}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">留空则使用平台默认模型</p>
                </div>
              </div>

              <div className="space-y-2">
                <Label className="flex items-center gap-1.5">
                  <Settings className="h-3.5 w-3.5 text-muted-foreground" />
                  模型备注
                </Label>
                <Input
                  placeholder="例如：高速生图、写实人像、视频主模型"
                  value={modelNote}
                  onChange={(e) => setModelNote(e.target.value)}
                />
                <p className="text-xs text-muted-foreground">创作界面选择模型时会优先显示备注，留空则显示模型名称</p>
              </div>

              {/* Row 3: API URL + API Key */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Globe className="h-3.5 w-3.5 text-muted-foreground" />
                    API 请求地址
                  </Label>
                  <Input
                    placeholder="https://api.openai.com/v1/images/generations"
                    value={apiUrl}
                    onChange={(e) => setApiUrl(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground">填写完整的 API 请求端点 URL</p>
                </div>
                <div className="space-y-2">
                  <Label className="flex items-center gap-1.5">
                    <Key className="h-3.5 w-3.5 text-muted-foreground" />
                    API Key <span className="text-destructive">*</span>
                  </Label>
                  <div className="relative">
                    <Input
                      type={showApiKey ? 'text' : 'password'}
                      placeholder="sk-..."
                      value={apiKey}
                      onChange={(e) => setApiKey(e.target.value)}
                      className="pr-10"
                    />
                    <button
                      type="button"
                      onClick={() => setShowApiKey(!showApiKey)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                    >
                      {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                </div>
              </div>

              {/* Actions */}
              <div className="flex flex-col gap-3 pt-2">
                <div className="flex items-center gap-3 flex-wrap">
                  <Button
                    className="gap-2"
                    onClick={handleAddKey}
                    disabled={!provider.trim() || (!editingKeyId && !apiKey.trim())}
                  >
                    <Check className="h-4 w-4" />
                    {editingKeyId ? '保存修改' : '确认添加'}
                  </Button>
                  <Button
                    variant="outline"
                    className="gap-2"
                    onClick={handleTestConnection}
                    disabled={!apiUrl.trim() || !apiKey.trim() || testing}
                  >
                    {testing ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Zap className="h-4 w-4" />
                    )}
                    {testing ? '测试中...' : '测试连接'}
                  </Button>
                  <Button
                    variant="outline"
                    className="gap-2"
                    onClick={handleFetchModels}
                    disabled={!apiUrl.trim() || !apiKey.trim() || fetchingModels}
                  >
                    {fetchingModels ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Cpu className="h-4 w-4" />
                    )}
                    {fetchingModels ? '获取中...' : '获取模型'}
                  </Button>
                  <Button variant="ghost" onClick={resetForm}>
                    取消
                  </Button>
                </div>
                {/* Test result */}
                {testResult && (
                  <div
                    className={`flex items-start gap-2 rounded-md px-3 py-2 text-sm ${
                      testResult.success
                        ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
                        : 'bg-destructive/10 text-destructive'
                    }`}
                  >
                    {testResult.success ? (
                      <Check className="h-4 w-4 mt-0.5 shrink-0" />
                    ) : (
                      <Shield className="h-4 w-4 mt-0.5 shrink-0" />
                    )}
                    <span>{testResult.message}</span>
                  </div>
                )}
                {/* Fetch models error */}
                {fetchModelsError && (
                  <div
                    className="flex items-start gap-2 rounded-md px-3 py-2 text-sm bg-destructive/10 text-destructive"
                  >
                    <Shield className="h-4 w-4 mt-0.5 shrink-0" />
                    <span>{fetchModelsError}</span>
                  </div>
                )}
                {/* Models list */}
                {models.length > 0 && (
                  <div className="mt-4 space-y-2">
                    <h4 className="font-medium text-sm">可用模型列表</h4>
                    <div className="border rounded-md p-3 max-h-60 overflow-y-auto">
                      {models.map((model) => (
                        <div
                          key={model.id}
                          className="p-2 rounded hover:bg-muted/50 cursor-pointer transition-colors"
                          onClick={() => setModelName(model.id)}
                        >
                          <div className="font-medium text-sm">{model.id}</div>
                          {model.description && (
                            <div className="text-xs text-muted-foreground mt-0.5">{model.description}</div>
                          )}
                        </div>
                      ))}
                    </div>
                    <p className="text-xs text-muted-foreground">点击模型名称自动填充到模型名称输入框</p>
                  </div>
                )}
              </div>
            </div>
          )}

          <Separator />

          {/* Configured keys list */}
          <div>
            <h3 className="font-medium mb-3">已配置的密钥</h3>
            {keys.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Key className="h-8 w-8 mx-auto mb-2 opacity-20" />
                <p className="text-sm">暂无配置的API密钥</p>
                <p className="text-xs mt-1">点击上方按钮添加你的第一个密钥</p>
              </div>
            ) : (
              <div className="space-y-3">
                {groupedKeys.map((group) => (
                  <div
                    key={group.name}
                    className="p-4 rounded-lg border border-border/80 bg-card transition-colors"
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0 space-y-2">
                        <div className="flex items-center gap-2 flex-wrap">
                          {group.provider === 'mozheAPI' && (
                            <div className="flex h-6 w-6 items-center justify-center rounded bg-primary/10 mr-1">
                              <img src="/icons/mozhe-api-logo.png" alt="mozheAPI" className="h-4 w-4 object-contain" />
                            </div>
                          )}
                          <span className="font-medium">{group.name}</span>
                          <Badge variant="outline" className="text-xs">{group.provider}</Badge>
                          <Badge variant="secondary" className="text-xs">{group.keys.length} 个模型</Badge>
                        </div>

                        <div className="space-y-2 pt-1">
                          {(['image', 'video', 'text'] as const).map(type => {
                            const typeKeys = group.keys.filter(key => key.type === type);
                            if (typeKeys.length === 0) return null;
                            return (
                              <div key={type} className="rounded-md border border-border/60 bg-muted/20 p-2">
                                <div className="mb-2 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                                  {type === 'image' ? <Image className="h-3.5 w-3.5" /> : type === 'video' ? <Film className="h-3.5 w-3.5" /> : <MessageSquare className="h-3.5 w-3.5" />}
                                  {type === 'image' ? '生图模型' : type === 'video' ? '视频模型' : '多模态模型'}
                                </div>
                                <div className="space-y-1.5">
                                  {typeKeys.map(key => (
                                    <div key={key.id} className={`flex flex-col gap-2 rounded-md px-2 py-2 sm:flex-row sm:items-center sm:justify-between ${key.isActive ? 'bg-background/70' : 'bg-muted/40 opacity-70'}`}>
                                      <div className="min-w-0">
                                        <div className="flex flex-wrap items-center gap-2">
                                          <span className="font-medium">{key.note || key.modelName || '默认模型'}</span>
                                          {key.note && <span className="text-xs text-muted-foreground">{key.modelName}</span>}
                                          <Badge variant="outline" className="font-mono text-xs">{key.apiKeyPreview}</Badge>
                                          {!key.isActive && <Badge variant="outline" className="text-muted-foreground">已禁用</Badge>}
                                        </div>
                                        <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
                                          {key.apiUrl && <span className="truncate"><Globe className="mr-1 inline h-3 w-3" />{key.apiUrl}</span>}
                                          <span><Calendar className="mr-1 inline h-3 w-3" />{key.createdAt}</span>
                                        </div>
                                      </div>
                                      <div className="flex shrink-0 items-center gap-1">
                                        <Button variant="ghost" size="sm" className="h-8 px-2" onClick={() => handleTestExistingKey(key.id)} disabled={testingKeyId === key.id} title="测试连接">
                                          {testingKeyId === key.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
                                        </Button>
                                        <Button variant="ghost" size="sm" className="h-8 px-2" onClick={() => handleEditKey(key.id)} title="编辑">
                                          <Settings className="h-4 w-4" />
                                        </Button>
                                        <Button variant="ghost" size="sm" className="h-8 px-2" onClick={() => toggleActive(key.id)} title={key.isActive ? '禁用' : '启用'}>
                                          {key.isActive ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
                                        </Button>
                                        <Button variant="ghost" size="sm" className="h-8 px-2 text-destructive hover:text-destructive" onClick={() => remove(key.id)} title="删除">
                                          <Trash2 className="h-4 w-4" />
                                        </Button>
                                      </div>
                                      {keyTestResults[key.id] && (
                                        <div className={`sm:hidden flex items-start gap-2 rounded-md px-3 py-1.5 text-xs ${keyTestResults[key.id].success ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400' : 'bg-destructive/10 text-destructive'}`}>
                                          {keyTestResults[key.id].success ? <Check className="h-3 w-3 mt-0.5 shrink-0" /> : <Shield className="h-3 w-3 mt-0.5 shrink-0" />}
                                          <span>{keyTestResults[key.id].message}</span>
                                        </div>
                                      )}
                                    </div>
                                  ))}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>

                      <div className="flex items-center gap-1 shrink-0">
                        <Button variant="outline" size="sm" className="gap-1.5" onClick={() => handleAddModelForProvider(group)}>
                          <Plus className="h-3.5 w-3.5" />加模型
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      <Dialog open={!!editingKeyId} onOpenChange={(open) => { if (!open) resetForm(); }}>
        <DialogContent className="max-w-3xl border-white/15 bg-background/85 backdrop-blur-2xl">
          <DialogHeader>
            <DialogTitle>编辑 API 密钥</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="flex items-center gap-1.5">
                  <Shield className="h-3.5 w-3.5 text-muted-foreground" />
                  供应商 <span className="text-destructive">*</span>
                </Label>
                <select
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                  value={provider}
                  onChange={(e) => handleProviderChange(e.target.value)}
                >
                  <option value="">选择供应商...</option>
                  {providerOptions.map((p) => (
                    <option key={p.name} value={p.name}>{p.name}</option>
                  ))}
                </select>
              </div>
              <div className="space-y-2">
                <Label>供应商名称</Label>
                <Input
                  placeholder="例如: 硅基流动, mozheAPI"
                  value={supplierName}
                  onChange={(e) => setSupplierName(e.target.value)}
                />
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>模型类型</Label>
                <Select value={formType} onValueChange={v => handleModelTypeChange(v as 'image' | 'video' | 'text')}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="image">生图模型</SelectItem>
                    <SelectItem value="video">视频模型</SelectItem>
                    <SelectItem value="text">多模态模型</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>模型名称</Label>
                <div className="relative">
                  <Input
                    placeholder={formType === 'image' ? '选择或输入生图模型' : formType === 'video' ? '选择或输入视频模型' : '选择或输入多模态模型'}
                    value={modelName}
                    onChange={(e) => {
                      handleModelNameChange(e.target.value);
                      setShowModelSuggestions(true);
                    }}
                    onClick={() => setShowModelSuggestions(true)}
                    onFocus={() => setShowModelSuggestions(true)}
                    onBlur={() => window.setTimeout(() => setShowModelSuggestions(false), 120)}
                  />
                  {showModelSuggestions && modelSuggestionOptions.length > 0 && (
                    <div className="absolute z-50 mt-1 max-h-56 w-full overflow-y-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md">
                      {modelSuggestionOptions.map((option) => (
                        <button
                          key={option.key}
                          type="button"
                          className="block w-full px-3 py-2 text-left text-sm hover:bg-accent hover:text-accent-foreground"
                          onMouseDown={(e) => {
                            e.preventDefault();
                            handleModelNameChange(option.value);
                            setShowModelSuggestions(false);
                          }}
                        >
                          <span className="block font-medium">{option.value}</span>
                          {option.label !== option.value && (
                            <span className="block text-xs text-muted-foreground">{option.label}</span>
                          )}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div className="space-y-2">
              <Label>模型备注</Label>
              <Input
                placeholder="例如：高速生图、写实人像、视频主模型"
                value={modelNote}
                onChange={(e) => setModelNote(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label>API 请求地址</Label>
              <Input
                placeholder="https://api.openai.com/v1/images/generations"
                value={apiUrl}
                onChange={(e) => setApiUrl(e.target.value)}
              />
            </div>

            <div className="space-y-2">
              <Label>API Key <span className="text-destructive">*</span></Label>
              <div className="relative">
                <Input
                  type={showApiKey ? 'text' : 'password'}
                  placeholder="sk-..."
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowApiKey(!showApiKey)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                >
                  {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {testResult && (
              <div className={`flex items-start gap-2 rounded-md px-3 py-2 text-sm ${
                testResult.success ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400' : 'bg-destructive/10 text-destructive'
              }`}>
                {testResult.success ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <Shield className="h-4 w-4 mt-0.5 shrink-0" />}
                <span>{testResult.message}</span>
              </div>
            )}

            <div className="flex flex-wrap justify-end gap-3 pt-2">
              <Button variant="outline" className="gap-2" onClick={handleTestConnection} disabled={!apiUrl.trim() || !apiKey.trim() || testing}>
                {testing ? <Loader2 className="h-4 w-4 animate-spin" /> : <Zap className="h-4 w-4" />}
                {testing ? '测试中...' : '测试连接'}
              </Button>
              <Button variant="outline" onClick={resetForm}>取消</Button>
              <Button className="gap-2" onClick={handleAddKey} disabled={!provider.trim() || (!editingKeyId && !apiKey.trim())}>
                <Check className="h-4 w-4" />保存修改
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
