'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/lib/auth-store';
import { useAdminConfig, type SystemApiConfig } from '@/lib/admin-store';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useSiteConfig } from '@/lib/site-config';
import type { ManagedApiProvider, ManagedModelRecommendation, ManagedModelType } from '@/lib/model-config-types';
import { Coins, Edit3, Film, Globe, Image, Key, MessageSquare, Plus, Save, Trash2 } from 'lucide-react';
import { toast } from 'sonner';

const MODEL_TYPE_LABELS: Record<ManagedModelType, string> = {
  image: '\u751f\u56fe\u6a21\u578b',
  video: '\u89c6\u9891\u6a21\u578b',
  text: '\u6587\u672c\u6a21\u578b',
};

const BILLING_MODE_LABELS: Record<'fixed' | 'ratio' | 'token', string> = {
  fixed: '固定积分',
  ratio: '倍率计费',
  token: 'Token 积分',
};

const SYSTEM_API_PROVIDER_OPTIONS = ['mozheAPI', 'New API'] as const;

function authHeaders(accessToken: string | null): HeadersInit {
  return {
    'Content-Type': 'application/json',
    ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
  };
}

function SectionMenu<T extends string>({
  items,
  activeValue,
  onChange,
}: {
  items: Array<{ value: T; label: string; description?: string }>;
  activeValue: T;
  onChange: (value: T) => void;
}) {
  return (
    <div className="overflow-x-auto rounded-lg border border-border bg-card p-1">
      <div className="flex min-w-max gap-1">
        {items.map(item => {
          const active = activeValue === item.value;
          return (
            <button
              key={item.value}
              type="button"
              onClick={() => onChange(item.value)}
              className={`min-w-40 rounded-md px-4 py-3 text-left transition-colors ${
                active ? 'bg-primary/10 text-primary' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground'
              }`}
            >
              <span className="block text-sm font-semibold">{item.label}</span>
              {item.description && <span className="mt-1 block text-xs opacity-75">{item.description}</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

type SystemApiGroup = {
  provider: string;
  modelGroup: string;
  apis: SystemApiConfig[];
};

type ApiManagementSection = 'providers' | 'recommendations' | 'system';
// ============================================================
// Tab 1: API Management
// ============================================================

export default function ApiManagementTab() {
  const { accessToken } = useAuth();
  const { config: siteConfig } = useSiteConfig();
  const { config, addSystemApi, updateSystemApi, removeSystemApi, toggleSystemApi } = useAdminConfig();
  const membershipEnabled = siteConfig.membershipEnabled !== false;
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [providers, setProviders] = useState<ManagedApiProvider[]>([]);
  const [recommendations, setRecommendations] = useState<ManagedModelRecommendation[]>([]);
  const [modelConfigLoading, setModelConfigLoading] = useState(false);
  const [providerSearch, setProviderSearch] = useState('');
  const [providerPage, setProviderPage] = useState(1);
  const [providerPageSize, setProviderPageSize] = useState(10);
  const [showProviderForm, setShowProviderForm] = useState(false);
  const [recommendationSearch, setRecommendationSearch] = useState('');
  const [recommendationPage, setRecommendationPage] = useState(1);
  const [recommendationPageSize, setRecommendationPageSize] = useState(10);
  const [showRecommendationForm, setShowRecommendationForm] = useState(false);
  const [activeSection, setActiveSection] = useState<ApiManagementSection>('providers');

  const [providerEditingId, setProviderEditingId] = useState<string | null>(null);
  const [providerName, setProviderName] = useState('');
  const [providerUrl, setProviderUrl] = useState('');
  const [providerModel, setProviderModel] = useState('');
  const [providerType, setProviderType] = useState<ManagedModelType>('image');
  const [providerWebsite, setProviderWebsite] = useState('');
  const [providerSortOrder, setProviderSortOrder] = useState('0');
  const [providerActive, setProviderActive] = useState(true);

  const [recommendationEditingId, setRecommendationEditingId] = useState<string | null>(null);
  const [recommendationModelName, setRecommendationModelName] = useState('');
  const [recommendationDisplayName, setRecommendationDisplayName] = useState('');
  const [recommendationType, setRecommendationType] = useState<ManagedModelType>('image');
  const [recommendationProviderId, setRecommendationProviderId] = useState('');
  const [recommendationSortOrder, setRecommendationSortOrder] = useState('0');
  const [recommendationActive, setRecommendationActive] = useState(true);

  // Form state
  const [formName, setFormName] = useState('');
  const [formProvider, setFormProvider] = useState('');
  const [formApiUrl, setFormApiUrl] = useState('');
  const [formModelName, setFormModelName] = useState('');
  const [formModelGroup, setFormModelGroup] = useState('default');
  const [formNote, setFormNote] = useState('');
  const [formApiKey, setFormApiKey] = useState('');
  const [formType, setFormType] = useState<'image' | 'video' | 'text'>('image');
  const [formCredits, setFormCredits] = useState('10');
  const [formBillingMode, setFormBillingMode] = useState<'fixed' | 'ratio' | 'token'>('fixed');
  const [formFixedPrice, setFormFixedPrice] = useState('0');
  const [formInputPricePer1K, setFormInputPricePer1K] = useState('0');
  const [formOutputPricePer1K, setFormOutputPricePer1K] = useState('0');
  const [formModelRatio, setFormModelRatio] = useState('1');
  const [formCompletionRatio, setFormCompletionRatio] = useState('1');
  const [formGroupRatio, setFormGroupRatio] = useState('1');
  const [formPriceNote, setFormPriceNote] = useState('');

  const providerSearchTerm = providerSearch.trim().toLowerCase();
  const filteredProviders = providerSearchTerm
    ? providers.filter(provider => [
        provider.name,
        provider.defaultApiUrl,
        provider.defaultModel,
        provider.website || '',
        MODEL_TYPE_LABELS[provider.type],
      ].join(' ').toLowerCase().includes(providerSearchTerm))
    : providers;
  const totalProviderPages = Math.max(1, Math.ceil(filteredProviders.length / providerPageSize));
  const visibleProviders = filteredProviders.slice(
    (providerPage - 1) * providerPageSize,
    providerPage * providerPageSize
  );
  const recommendationSearchTerm = recommendationSearch.trim().toLowerCase();
  const filteredRecommendations = recommendationSearchTerm
    ? recommendations.filter(recommendation => {
        const boundProvider = providers.find(provider => provider.id === recommendation.providerId);
        return [
          recommendation.modelName,
          recommendation.displayName,
          MODEL_TYPE_LABELS[recommendation.type],
          boundProvider?.name || '全部供应商',
        ].join(' ').toLowerCase().includes(recommendationSearchTerm);
      })
    : recommendations;
  const totalRecommendationPages = Math.max(1, Math.ceil(filteredRecommendations.length / recommendationPageSize));
  const visibleRecommendations = filteredRecommendations.slice(
    (recommendationPage - 1) * recommendationPageSize,
    recommendationPage * recommendationPageSize
  );

  const fetchModelConfig = useCallback(async () => {
    setModelConfigLoading(true);
    try {
      const [providersRes, recommendationsRes] = await Promise.all([
        fetch('/api/admin/providers'),
        fetch('/api/admin/model-recommendations'),
      ]);
      const providersData = await providersRes.json();
      const recommendationsData = await recommendationsRes.json();
      setProviders(providersData.providers || []);
      setRecommendations(recommendationsData.recommendations || []);
    } catch {
      toast.error('模型配置加载失败');
    } finally {
      setModelConfigLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchModelConfig();
  }, [fetchModelConfig]);

  useEffect(() => {
    setProviderPage(page => Math.min(page, totalProviderPages));
  }, [totalProviderPages]);

  useEffect(() => {
    setRecommendationPage(page => Math.min(page, totalRecommendationPages));
  }, [totalRecommendationPages]);

  const resetProviderForm = () => {
    setProviderEditingId(null);
    setProviderName('');
    setProviderUrl('');
    setProviderModel('');
    setProviderType('image');
    setProviderWebsite('');
    setProviderSortOrder('0');
    setProviderActive(true);
  };

  const startProviderEdit = (provider: ManagedApiProvider) => {
    setProviderEditingId(provider.id);
    setProviderName(provider.name);
    setProviderUrl(provider.defaultApiUrl);
    setProviderModel(provider.defaultModel);
    setProviderType(provider.type);
    setProviderWebsite(provider.website || '');
    setProviderSortOrder(String(provider.sortOrder));
    setProviderActive(provider.isActive);
  };

  const saveProvider = async () => {
    if (!providerName.trim()) {
      toast.error('请填写供应商名称');
      return;
    }
    try {
      const res = await fetch('/api/admin/providers', {
        method: providerEditingId ? 'PUT' : 'POST',
        headers: authHeaders(accessToken),
        body: JSON.stringify({
          id: providerEditingId,
          name: providerName,
          defaultApiUrl: providerUrl,
          defaultModel: providerModel,
          type: providerType,
          website: providerWebsite,
          isActive: providerActive,
          sortOrder: Number(providerSortOrder) || 0,
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '保存失败');
      toast.success(providerEditingId ? '供应商已更新' : '供应商已添加');
      resetProviderForm();
      setShowProviderForm(false);
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '保存失败');
    }
  };

  const toggleProvider = async (provider: ManagedApiProvider) => {
    try {
      const res = await fetch('/api/admin/providers', {
        method: 'PUT',
        headers: authHeaders(accessToken),
        body: JSON.stringify({ ...provider, isActive: !provider.isActive }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '操作失败');
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '操作失败');
    }
  };

  const deleteProvider = async (id: string) => {
    try {
      const res = await fetch('/api/admin/providers', {
        method: 'DELETE',
        headers: authHeaders(accessToken),
        body: JSON.stringify({ id }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '删除失败');
      toast.success('供应商已删除');
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '删除失败');
    }
  };

  const resetRecommendationForm = () => {
    setRecommendationEditingId(null);
    setRecommendationModelName('');
    setRecommendationDisplayName('');
    setRecommendationType('image');
    setRecommendationProviderId('');
    setRecommendationSortOrder('0');
    setRecommendationActive(true);
  };

  const startRecommendationEdit = (recommendation: ManagedModelRecommendation) => {
    setRecommendationEditingId(recommendation.id);
    setRecommendationModelName(recommendation.modelName);
    setRecommendationDisplayName(recommendation.displayName);
    setRecommendationType(recommendation.type);
    setRecommendationProviderId(recommendation.providerId || '');
    setRecommendationSortOrder(String(recommendation.sortOrder));
    setRecommendationActive(recommendation.isActive);
  };

  const saveRecommendation = async () => {
    if (!recommendationModelName.trim()) {
      toast.error('请填写模型名称');
      return;
    }
    try {
      const res = await fetch('/api/admin/model-recommendations', {
        method: recommendationEditingId ? 'PUT' : 'POST',
        headers: authHeaders(accessToken),
        body: JSON.stringify({
          id: recommendationEditingId,
          modelName: recommendationModelName,
          displayName: recommendationDisplayName || recommendationModelName,
          type: recommendationType,
          providerId: recommendationProviderId || null,
          isActive: recommendationActive,
          sortOrder: Number(recommendationSortOrder) || 0,
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '保存失败');
      toast.success(recommendationEditingId ? '推荐模型已更新' : '推荐模型已添加');
      resetRecommendationForm();
      setShowRecommendationForm(false);
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '保存失败');
    }
  };

  const toggleRecommendation = async (recommendation: ManagedModelRecommendation) => {
    try {
      const res = await fetch('/api/admin/model-recommendations', {
        method: 'PUT',
        headers: authHeaders(accessToken),
        body: JSON.stringify({ ...recommendation, isActive: !recommendation.isActive }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '操作失败');
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '操作失败');
    }
  };

  const deleteRecommendation = async (id: string) => {
    try {
      const res = await fetch('/api/admin/model-recommendations', {
        method: 'DELETE',
        headers: authHeaders(accessToken),
        body: JSON.stringify({ id }),
      });
      if (!res.ok) throw new Error((await res.json()).error || '删除失败');
      toast.success('推荐模型已删除');
      fetchModelConfig();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '删除失败');
    }
  };

  const resetForm = () => {
    setFormName(''); setFormProvider(''); setFormApiUrl(''); setFormModelName(''); setFormModelGroup('default'); setFormNote(''); setFormApiKey('');
    setFormType('image'); setFormCredits('10'); setFormBillingMode('fixed'); setFormFixedPrice('0'); setFormInputPricePer1K('0'); setFormOutputPricePer1K('0');
    setFormModelRatio('1'); setFormCompletionRatio('1'); setFormGroupRatio('1'); setFormPriceNote(''); setEditingId(null); setShowForm(false);
  };

  const startEdit = (api: SystemApiConfig) => {
    setFormName(api.name); setFormProvider(api.provider || ''); setFormApiUrl(api.apiUrl); setFormModelName(api.modelName); setFormNote(api.note || '');
    setFormModelGroup(api.modelGroup || 'default'); setFormApiKey(''); setFormType(api.type); setFormCredits(String(api.creditsPerUse));
    setFormBillingMode(api.billingMode || 'fixed'); setFormFixedPrice(String(api.fixedPrice ?? 0));
    setFormInputPricePer1K(String(api.inputPricePer1K ?? 0)); setFormOutputPricePer1K(String(api.outputPricePer1K ?? 0));
    setFormModelRatio(String(api.modelRatio ?? 1)); setFormCompletionRatio(String(api.completionRatio ?? 1));
    setFormGroupRatio(String(api.groupRatio ?? 1)); setFormPriceNote(api.priceNote || '');
    setEditingId(api.id); setShowForm(false);
  };

  const handleSave = async () => {
    if (!formName || !formModelName) {
      toast.error('请填写模型名称和显示名称');
      return;
    }
    const data = {
      name: formName,
      provider: formProvider,
      apiUrl: formApiUrl,
      modelName: formModelName,
      modelGroup: formModelGroup || 'default',
      note: formNote,
      apiKey: formApiKey,
      type: formType,
      creditsPerUse: Number(formCredits) || 10,
      billingMode: formBillingMode,
      fixedPrice: Number(formFixedPrice) || 0,
      inputPricePer1K: Number(formInputPricePer1K) || 0,
      outputPricePer1K: Number(formOutputPricePer1K) || 0,
      modelRatio: Number(formModelRatio) || 1,
      completionRatio: Number(formCompletionRatio) || 1,
      groupRatio: Number(formGroupRatio) || 1,
      priceNote: formPriceNote,
      isActive: true,
    };

    try {
      if (editingId) {
        await updateSystemApi(editingId, data);
        toast.success('API 已更新');
      } else {
        await addSystemApi(data);
        toast.success('API 已添加');
      }
      resetForm();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '保存失败');
    }
  };

  const systemApiGroups: SystemApiGroup[] = Object.values(config.systemApis.reduce<Record<string, SystemApiGroup>>((acc, api) => {
    const providerName = api.provider || '未命名供应商';
    const modelGroup = api.modelGroup || 'default';
    const groupKey = `${providerName}::${modelGroup}`;
    if (!acc[groupKey]) acc[groupKey] = { provider: providerName, modelGroup, apis: [] };
    acc[groupKey].apis.push(api);
    return acc;
  }, {}));

  const startAddSystemApiForProvider = (group: SystemApiGroup) => {
    const seed = group.apis[0];
    resetForm();
    setFormProvider(group.provider);
    setFormModelGroup(group.modelGroup || 'default');
    setFormApiUrl(seed?.apiUrl || '');
    setFormApiKey('');
    setFormType(seed?.type || 'image');
    setShowForm(true);
  };

  const renderSystemProviderField = () => (
    <div className="space-y-2">
      <Label>供应商</Label>
      <Input placeholder="如: mozheAPI / New API" value={formProvider} onChange={e => setFormProvider(e.target.value)} />
      <div className="flex flex-wrap gap-2">
        {SYSTEM_API_PROVIDER_OPTIONS.map(providerName => (
          <Button
            key={providerName}
            type="button"
            variant={formProvider === providerName ? 'default' : 'outline'}
            size="sm"
            onClick={() => setFormProvider(providerName)}
          >
            {providerName}
          </Button>
        ))}
      </div>
      <p className="text-xs text-muted-foreground">只有选择 New API 时才会启用 NewAPI 兼容参数；mozheAPI 和其他供应商保持原调用参数。</p>
    </div>
  );

  const renderPricingFields = () => (
    <div className="space-y-4 rounded-lg border border-border/70 bg-muted/20 p-4">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h4 className="text-sm font-semibold">模型分组与定价</h4>
          <p className="text-xs text-muted-foreground">参考 New API 的模型分组和倍率设置；这里配置的是平台全局积分定价。</p>
        </div>
        <Badge variant="outline">{BILLING_MODE_LABELS[formBillingMode]}</Badge>
      </div>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
        <div className="space-y-2">
          <Label>模型分组</Label>
          <Input placeholder="default / vip / image" value={formModelGroup} onChange={e => setFormModelGroup(e.target.value)} />
        </div>
        <div className="space-y-2">
          <Label>计费模式</Label>
          <Select value={formBillingMode} onValueChange={v => setFormBillingMode(v as 'fixed' | 'ratio' | 'token')}>
            <SelectTrigger><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="fixed">固定积分</SelectItem>
              <SelectItem value="ratio">倍率计费</SelectItem>
              <SelectItem value="token">Token 积分</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-2">
          <Label>固定积分</Label>
          <Input type="number" step="0.0001" value={formFixedPrice} onChange={e => setFormFixedPrice(e.target.value)} />
        </div>
      </div>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
        <div className="space-y-2">
          <Label>模型倍率</Label>
          <Input type="number" step="0.000001" value={formModelRatio} onChange={e => setFormModelRatio(e.target.value)} />
        </div>
        <div className="space-y-2">
          <Label>补全倍率</Label>
          <Input type="number" step="0.000001" value={formCompletionRatio} onChange={e => setFormCompletionRatio(e.target.value)} />
        </div>
        <div className="space-y-2">
          <Label>分组倍率</Label>
          <Input type="number" step="0.000001" value={formGroupRatio} onChange={e => setFormGroupRatio(e.target.value)} />
        </div>
      </div>
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <div className="space-y-2">
          <Label>输入积分 / 1K tokens</Label>
          <Input type="number" step="0.000001" value={formInputPricePer1K} onChange={e => setFormInputPricePer1K(e.target.value)} />
        </div>
        <div className="space-y-2">
          <Label>输出积分 / 1K tokens</Label>
          <Input type="number" step="0.000001" value={formOutputPricePer1K} onChange={e => setFormOutputPricePer1K(e.target.value)} />
        </div>
      </div>
      <div className="space-y-2">
        <Label>价格备注</Label>
        <Input placeholder="例如：全局基础价 10 积分，VIP 分组 0.8x" value={formPriceNote} onChange={e => setFormPriceNote(e.target.value)} />
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      <SectionMenu
        items={[
          { value: 'providers', label: '供应商管理', description: `${providers.length} 个供应商` },
          { value: 'recommendations', label: '推荐模型管理', description: `${recommendations.length} 个模型` },
          { value: 'system', label: '系统默认 API', description: membershipEnabled ? `${config.systemApis.length} 个 API` : '会员功能关闭' },
        ]}
        activeValue={activeSection}
        onChange={setActiveSection}
      />

      {activeSection === 'providers' && (
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">供应商管理</CardTitle>
              <CardDescription>维护个人中心 API 管理里的供应商列表、默认地址和默认模型</CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={fetchModelConfig} disabled={modelConfigLoading}>
              {modelConfigLoading ? '刷新中...' : '刷新'}
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
              <Input
                className="sm:w-[420px]"
                value={providerSearch}
                onChange={event => {
                  setProviderSearch(event.target.value);
                  setProviderPage(1);
                }}
                placeholder="搜索供应商名称、模型、API 地址、官网"
              />
              <Button
                className="gap-1.5"
                onClick={() => {
                  resetProviderForm();
                  setShowProviderForm(true);
                }}
              >
                <Plus className="h-4 w-4" />添加供应商
              </Button>
            </div>
            <div className="text-xs text-muted-foreground">
              共 {providers.length} 个供应商，当前显示 {filteredProviders.length} 个
            </div>
          </div>
          <div className="space-y-2">
            {providers.length === 0 ? (
              <div className="text-center py-6 text-sm text-muted-foreground border rounded-lg">暂无供应商</div>
            ) : filteredProviders.length === 0 ? (
              <div className="text-center py-6 text-sm text-muted-foreground border rounded-lg">没有匹配的供应商</div>
            ) : visibleProviders.map(provider => (
              <div key={provider.id} className="flex items-center gap-3 p-3 rounded-lg border border-border">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-medium">{provider.name}</span>
                    <Badge variant={provider.isActive ? 'default' : 'secondary'}>{provider.isActive ? '已启用' : '已停用'}</Badge>
                    <Badge variant="outline">{MODEL_TYPE_LABELS[provider.type]}</Badge>
                  </div>
                  <div className="text-xs text-muted-foreground mt-1 truncate">
                    {provider.defaultModel || '无默认模型'} · {provider.defaultApiUrl || '无默认地址'}
                  </div>
                </div>
                <Switch checked={provider.isActive} onCheckedChange={() => toggleProvider(provider)} />
                <Button variant="ghost" size="sm" onClick={() => startProviderEdit(provider)}><Edit3 className="h-4 w-4" /></Button>
                <Button variant="ghost" size="sm" className="text-destructive" onClick={() => deleteProvider(provider.id)}><Trash2 className="h-4 w-4" /></Button>
              </div>
            ))}
          </div>
          {filteredProviders.length > 0 && (
            <div className="flex flex-col gap-3 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-center gap-3 text-xs text-muted-foreground">
                <span>第 {providerPage} / {totalProviderPages} 页</span>
                <Select
                  value={String(providerPageSize)}
                  onValueChange={value => {
                    setProviderPageSize(Number(value));
                    setProviderPage(1);
                  }}
                >
                  <SelectTrigger className="h-11 w-[112px] px-4 text-base leading-none [&_[data-slot=select-value]]:leading-none">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent side="top" align="start" sideOffset={8}>
                    <SelectItem value="10">10/页</SelectItem>
                    <SelectItem value="20">20/页</SelectItem>
                    <SelectItem value="50">50/页</SelectItem>
                  </SelectContent>
                </Select>
                <span>共 {filteredProviders.length} 个供应商</span>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={providerPage <= 1 || modelConfigLoading}
                  onClick={() => setProviderPage(page => Math.max(1, page - 1))}
                >
                  上一页
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={providerPage >= totalProviderPages || modelConfigLoading}
                  onClick={() => setProviderPage(page => Math.min(totalProviderPages, page + 1))}
                >
                  下一页
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      )}

      {activeSection === 'recommendations' && (
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">推荐模型管理</CardTitle>
          <CardDescription>维护模型名称输入框的下拉推荐项；未绑定供应商的推荐会对同类型所有供应商显示</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
              <Input
                className="sm:w-[420px]"
                value={recommendationSearch}
                onChange={event => {
                  setRecommendationSearch(event.target.value);
                  setRecommendationPage(1);
                }}
                placeholder="搜索模型名称、显示名称、类型、绑定供应商"
              />
              <Button
                className="gap-1.5"
                onClick={() => {
                  resetRecommendationForm();
                  setShowRecommendationForm(true);
                }}
              >
                <Plus className="h-4 w-4" />添加推荐模型
              </Button>
            </div>
            <div className="text-xs text-muted-foreground">
              共 {recommendations.length} 个推荐模型，当前显示 {filteredRecommendations.length} 个
            </div>
          </div>
          <div className="space-y-2">
            {recommendations.length === 0 ? (
              <div className="text-center py-6 text-sm text-muted-foreground border rounded-lg">暂无推荐模型</div>
            ) : filteredRecommendations.length === 0 ? (
              <div className="text-center py-6 text-sm text-muted-foreground border rounded-lg">没有匹配的推荐模型</div>
            ) : visibleRecommendations.map(recommendation => {
              const boundProvider = providers.find(provider => provider.id === recommendation.providerId);
              return (
                <div key={recommendation.id} className="flex items-center gap-3 p-3 rounded-lg border border-border">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="font-medium">{recommendation.modelName}</span>
                      <Badge variant={recommendation.isActive ? 'default' : 'secondary'}>{recommendation.isActive ? '已启用' : '已停用'}</Badge>
                      <Badge variant="outline">{MODEL_TYPE_LABELS[recommendation.type]}</Badge>
                      <Badge variant="outline">{boundProvider?.name || '全部供应商'}</Badge>
                    </div>
                    <div className="text-xs text-muted-foreground mt-1">
                      {recommendation.displayName || recommendation.modelName}
                    </div>
                  </div>
                  <Switch checked={recommendation.isActive} onCheckedChange={() => toggleRecommendation(recommendation)} />
                  <Button variant="ghost" size="sm" onClick={() => startRecommendationEdit(recommendation)}><Edit3 className="h-4 w-4" /></Button>
                  <Button variant="ghost" size="sm" className="text-destructive" onClick={() => deleteRecommendation(recommendation.id)}><Trash2 className="h-4 w-4" /></Button>
                </div>
              );
            })}
          </div>
          {filteredRecommendations.length > 0 && (
            <div className="flex flex-col gap-3 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-center gap-3 text-xs text-muted-foreground">
                <span>第 {recommendationPage} / {totalRecommendationPages} 页</span>
                <Select
                  value={String(recommendationPageSize)}
                  onValueChange={value => {
                    setRecommendationPageSize(Number(value));
                    setRecommendationPage(1);
                  }}
                >
                  <SelectTrigger className="h-11 w-[112px] px-4 text-base leading-none [&_[data-slot=select-value]]:leading-none">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent side="top" align="start" sideOffset={8}>
                    <SelectItem value="10">10/页</SelectItem>
                    <SelectItem value="20">20/页</SelectItem>
                    <SelectItem value="50">50/页</SelectItem>
                  </SelectContent>
                </Select>
                <span>共 {filteredRecommendations.length} 个推荐模型</span>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={recommendationPage <= 1 || modelConfigLoading}
                  onClick={() => setRecommendationPage(page => Math.max(1, page - 1))}
                >
                  上一页
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={recommendationPage >= totalRecommendationPages || modelConfigLoading}
                  onClick={() => setRecommendationPage(page => Math.min(totalRecommendationPages, page + 1))}
                >
                  下一页
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      )}

      {activeSection === 'system' && (
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">系统默认 API</CardTitle>
              <CardDescription>{membershipEnabled ? '配置所有用户可使用的内置模型 API、全局积分价格和模型分组' : '会员功能已关闭，系统默认 API 设置不可用'}</CardDescription>
            </div>
            {membershipEnabled && (
              <Button size="sm" className="gap-1.5" onClick={() => { resetForm(); setShowForm(true); }}>
                <Plus className="h-4 w-4" />添加 API
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {/* API List */}
          {!membershipEnabled ? (
            <div className="rounded-lg border border-border p-4 text-sm text-muted-foreground">
              当前平台不显示会员、积分和额度信息，用户创作时也不会显示积分消耗，因此后台暂不允许配置系统默认 API。
            </div>
          ) : config.systemApis.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <Key className="h-8 w-8 mx-auto mb-2 opacity-50" />
              <p>暂无系统 API，请添加</p>
            </div>
          ) : (
            <div className="space-y-3">
              {systemApiGroups.map(group => (
                <div key={`${group.provider}-${group.modelGroup}`} className="rounded-lg border border-border p-4">
                  <div className="mb-3 flex items-center justify-between gap-3">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{group.provider}</span>
                        <Badge variant="outline" className="text-xs">分组：{group.modelGroup}</Badge>
                        <Badge variant="secondary" className="text-xs">{group.apis.length} 个模型</Badge>
                      </div>
                      <p className="mt-1 truncate text-xs text-muted-foreground">{group.apis[0]?.apiUrl || '未设置默认 API 地址'}</p>
                    </div>
                    <Button variant="outline" size="sm" className="gap-1.5" onClick={() => startAddSystemApiForProvider(group)}>
                      <Plus className="h-3.5 w-3.5" />加模型
                    </Button>
                  </div>
                  <div className="space-y-2">
                    {(['image', 'video', 'text'] as const).map(type => {
                      const apis = group.apis.filter(api => api.type === type);
                      if (apis.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">
                            {apis.map(api => (
                              <div key={api.id} className={`flex flex-col gap-2 rounded-md px-2 py-2 sm:flex-row sm:items-center sm:justify-between ${api.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">{api.note || api.name || api.modelName}</span>
                                    <Badge variant={api.isActive ? 'default' : 'secondary'} className="text-xs">{api.isActive ? '已启用' : '未启用'}</Badge>
                                    {api.note && <span className="text-xs text-muted-foreground">{api.modelName}</span>}
                                    <span className="text-xs text-muted-foreground"><Coins className="mr-1 inline h-3 w-3" />{api.creditsPerUse} 积分/次</span>
                                    <Badge variant="outline" className="text-xs">{BILLING_MODE_LABELS[api.billingMode || 'fixed']}</Badge>
                                  </div>
                                  <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
                                    {api.apiUrl && <span className="truncate"><Globe className="mr-1 inline h-3 w-3" />{api.apiUrl.slice(0, 64)}...</span>}
                                    <span>
                                      <Key className="mr-1 inline h-3 w-3" />
                                      {api.apiKeyPreview || '未设置密钥'}
                                    </span>
                                    <span>固定积分 {api.fixedPrice ?? 0}</span>
                                    <span>模型倍率 {api.modelRatio ?? 1}</span>
                                    <span>补全倍率 {api.completionRatio ?? 1}</span>
                                    <span>分组倍率 {api.groupRatio ?? 1}</span>
                                    {api.priceNote && <span>{api.priceNote}</span>}
                                  </div>
                                </div>
                                <div className="flex shrink-0 items-center gap-2">
                                  <Switch
                                    checked={api.isActive}
                                    onCheckedChange={() => {
                                      toggleSystemApi(api.id).catch(err => {
                                        toast.error(err instanceof Error ? err.message : '操作失败');
                                      });
                                    }}
                                  />
                                  <Button variant="ghost" size="sm" onClick={() => startEdit(api)}><Edit3 className="h-4 w-4" /></Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="text-destructive"
                                    onClick={() => {
                                      removeSystemApi(api.id)
                                        .then(() => toast.success('已删除'))
                                        .catch(err => toast.error(err instanceof Error ? err.message : '删除失败'));
                                    }}
                                  >
                                    <Trash2 className="h-4 w-4" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
      )}

      {/* Add API Dialog */}
      {membershipEnabled && activeSection === 'system' && showForm && (
        <Dialog open={showForm} onOpenChange={(open) => { setShowForm(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 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>显示名称</Label>
                <Input placeholder="如: See Dream v5.0" value={formName} onChange={e => setFormName(e.target.value)} />
              </div>
              {renderSystemProviderField()}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={formType} onValueChange={v => setFormType(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>
            <div className="space-y-2">
              <Label>模型备注</Label>
              <Input placeholder="例如：高速生图、写实人像、视频主模型" value={formNote} onChange={e => setFormNote(e.target.value)} />
              <p className="text-xs text-muted-foreground">创作界面选择模型时会优先显示备注，留空则显示模型名称</p>
            </div>
            <div className="space-y-2">
              <Label>API 请求地址</Label>
              <Input placeholder="https://api.example.com/v1/images/generations" value={formApiUrl} onChange={e => setFormApiUrl(e.target.value)} />
              <p className="text-xs text-muted-foreground">留空则使用平台内置 SDK</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>模型名称 (model)</Label>
                <Input placeholder="如: gpt-image-2" value={formModelName} onChange={e => setFormModelName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>每次消耗积分</Label>
                <Input type="number" value={formCredits} onChange={e => setFormCredits(e.target.value)} />
              </div>
            </div>
            {renderPricingFields()}
            <div className="space-y-2">
              <Label>API Key</Label>
              <Input type="password" placeholder="sk-..." value={formApiKey} onChange={e => setFormApiKey(e.target.value)} />
            </div>
            <div className="flex gap-3 justify-end">
              <Button variant="outline" onClick={resetForm}>取消</Button>
              <Button className="gap-1.5" onClick={handleSave}>
                <Save className="h-4 w-4" />添加
              </Button>
            </div>
            </div>
          </DialogContent>
        </Dialog>
      )}

      <Dialog open={showProviderForm} onOpenChange={(open) => { setShowProviderForm(open); if (!open) resetProviderForm(); }}>
        <DialogContent className="max-w-3xl border-white/15 bg-background/85 backdrop-blur-2xl">
          <DialogHeader>
            <DialogTitle>添加供应商</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>名称</Label>
                <Input value={providerName} onChange={e => setProviderName(e.target.value)} placeholder="mozheAPI" />
              </div>
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={providerType} onValueChange={v => setProviderType(v as ManagedModelType)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="image">生图</SelectItem>
                    <SelectItem value="video">视频</SelectItem>
                    <SelectItem value="text">文本</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>默认 API 地址</Label>
              <Input value={providerUrl} onChange={e => setProviderUrl(e.target.value)} placeholder="https://..." />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>默认模型</Label>
                <Input value={providerModel} onChange={e => setProviderModel(e.target.value)} placeholder="gpt-image-2" />
              </div>
              <div className="space-y-2">
                <Label>排序</Label>
                <Input type="number" value={providerSortOrder} onChange={e => setProviderSortOrder(e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>官网</Label>
              <Input value={providerWebsite} onChange={e => setProviderWebsite(e.target.value)} placeholder="https://..." />
            </div>
            <div className="flex items-center gap-2">
              <Switch checked={providerActive} onCheckedChange={setProviderActive} />
              <Label>启用</Label>
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={() => { setShowProviderForm(false); resetProviderForm(); }}>取消</Button>
              <Button className="gap-1.5" onClick={saveProvider}>
                <Save className="h-4 w-4" />添加
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={!!providerEditingId} onOpenChange={(open) => { if (!open) resetProviderForm(); }}>
        <DialogContent className="max-w-3xl border-white/15 bg-background/85 backdrop-blur-2xl">
          <DialogHeader>
            <DialogTitle>编辑供应商</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>名称</Label>
                <Input value={providerName} onChange={e => setProviderName(e.target.value)} placeholder="mozheAPI" />
              </div>
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={providerType} onValueChange={v => setProviderType(v as ManagedModelType)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="image">生图</SelectItem>
                    <SelectItem value="video">视频</SelectItem>
                    <SelectItem value="text">文本</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>默认 API 地址</Label>
              <Input value={providerUrl} onChange={e => setProviderUrl(e.target.value)} placeholder="https://..." />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>默认模型</Label>
                <Input value={providerModel} onChange={e => setProviderModel(e.target.value)} placeholder="gpt-image-2" />
              </div>
              <div className="space-y-2">
                <Label>排序</Label>
                <Input type="number" value={providerSortOrder} onChange={e => setProviderSortOrder(e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>官网</Label>
              <Input value={providerWebsite} onChange={e => setProviderWebsite(e.target.value)} placeholder="https://..." />
            </div>
            <div className="flex items-center gap-2">
              <Switch checked={providerActive} onCheckedChange={setProviderActive} />
              <Label>启用</Label>
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={resetProviderForm}>取消</Button>
              <Button className="gap-1.5" onClick={saveProvider}>
                <Save className="h-4 w-4" />保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={showRecommendationForm} onOpenChange={(open) => { setShowRecommendationForm(open); if (!open) resetRecommendationForm(); }}>
        <DialogContent className="max-w-3xl border-white/15 bg-background/85 backdrop-blur-2xl">
          <DialogHeader>
            <DialogTitle>添加推荐模型</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>模型名称</Label>
                <Input value={recommendationModelName} onChange={e => setRecommendationModelName(e.target.value)} placeholder="gpt-image-2" />
              </div>
              <div className="space-y-2">
                <Label>显示名称</Label>
                <Input value={recommendationDisplayName} onChange={e => setRecommendationDisplayName(e.target.value)} placeholder="留空则使用模型名称" />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={recommendationType} onValueChange={v => setRecommendationType(v as ManagedModelType)}>
                  <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>
                <Input type="number" value={recommendationSortOrder} onChange={e => setRecommendationSortOrder(e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>绑定供应商</Label>
              <Select
                value={recommendationProviderId || '__global__'}
                onValueChange={v => setRecommendationProviderId(v === '__global__' ? '' : v)}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__global__">全部同类型供应商</SelectItem>
                  {providers.map(provider => (
                    <SelectItem key={provider.id} value={provider.id}>{provider.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center gap-2">
              <Switch checked={recommendationActive} onCheckedChange={setRecommendationActive} />
              <Label>启用</Label>
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={() => { setShowRecommendationForm(false); resetRecommendationForm(); }}>取消</Button>
              <Button className="gap-1.5" onClick={saveRecommendation}>
                <Save className="h-4 w-4" />添加
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={!!recommendationEditingId} onOpenChange={(open) => { if (!open) resetRecommendationForm(); }}>
        <DialogContent className="max-w-3xl border-white/15 bg-background/85 backdrop-blur-2xl">
          <DialogHeader>
            <DialogTitle>编辑推荐模型</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>模型名称</Label>
                <Input value={recommendationModelName} onChange={e => setRecommendationModelName(e.target.value)} placeholder="gpt-image-2" />
              </div>
              <div className="space-y-2">
                <Label>显示名称</Label>
                <Input value={recommendationDisplayName} onChange={e => setRecommendationDisplayName(e.target.value)} placeholder="留空则使用模型名称" />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={recommendationType} onValueChange={v => setRecommendationType(v as ManagedModelType)}>
                  <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>
                <Input type="number" value={recommendationSortOrder} onChange={e => setRecommendationSortOrder(e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>绑定供应商</Label>
              <Select
                value={recommendationProviderId || '__global__'}
                onValueChange={v => setRecommendationProviderId(v === '__global__' ? '' : v)}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__global__">全部同类型供应商</SelectItem>
                  {providers.map(provider => (
                    <SelectItem key={provider.id} value={provider.id}>{provider.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-center gap-2">
              <Switch checked={recommendationActive} onCheckedChange={setRecommendationActive} />
              <Label>启用</Label>
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={resetRecommendationForm}>取消</Button>
              <Button className="gap-1.5" onClick={saveRecommendation}>
                <Save className="h-4 w-4" />保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={!!editingId} 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 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>显示名称</Label>
                <Input placeholder="如: See Dream v5.0" value={formName} onChange={e => setFormName(e.target.value)} />
              </div>
              {renderSystemProviderField()}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>类型</Label>
                <Select value={formType} onValueChange={v => setFormType(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>
            <div className="space-y-2">
              <Label>API 请求地址</Label>
              <Input placeholder="https://api.example.com/v1/images/generations" value={formApiUrl} onChange={e => setFormApiUrl(e.target.value)} />
              <p className="text-xs text-muted-foreground">留空则使用平台内置 SDK</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>模型名称 (model)</Label>
                <Input placeholder="如: gpt-image-2" value={formModelName} onChange={e => setFormModelName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>每次消耗积分</Label>
                <Input type="number" value={formCredits} onChange={e => setFormCredits(e.target.value)} />
              </div>
            </div>
            {renderPricingFields()}
            <div className="space-y-2">
              <Label>模型备注</Label>
              <Input placeholder="例如：高速生图、写实人像、视频主模型" value={formNote} onChange={e => setFormNote(e.target.value)} />
              <p className="text-xs text-muted-foreground">创作界面选择模型时会优先显示备注，留空则显示模型名称</p>
            </div>
            <div className="space-y-2">
              <Label>API Key</Label>
              <Input type="password" placeholder="留空则不修改已保存密钥" value={formApiKey} onChange={e => setFormApiKey(e.target.value)} />
            </div>
            <div className="flex justify-end gap-3 pt-2">
              <Button variant="outline" onClick={resetForm}>取消</Button>
              <Button className="gap-1.5" onClick={handleSave}>
                <Save className="h-4 w-4" />保存
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
