import { useEffect, useMemo, useRef, useState } from 'react';
import { Cpu, Check, Plus, RefreshCw, Trash2, Pencil, Eye } from 'lucide-react';
import { t } from '@/lib/i18n';
import {
  loadTrialModels,
  deleteModelConfiguration,
  loadConfiguredModels,
  saveModelConfiguration,
  updateModelConfiguration,
  type ModelInfo,
} from '@/lib/models';
import { PROVIDER_PRESETS } from '@/lib/providerPresets';

export default function ModelSwitch() {
  const [configuredModels, setConfiguredModels] = useState<ModelInfo[]>([]);
  const [trialModels, setTrialModels] = useState<ModelInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [provider, setProvider] = useState(PROVIDER_PRESETS[0]?.providers[0]?.id ?? 'openrouter');
  const [model, setModel] = useState('');
  const [apiKey, setApiKey] = useState('');
  const [baseUrl, setBaseUrl] = useState('');
  const [editingTarget, setEditingTarget] = useState<{ provider: string; model: string } | null>(null);
  const [viewingModelKey, setViewingModelKey] = useState<string | null>(null);
  const editorCardRef = useRef<HTMLDivElement | null>(null);

  const providerOptions = useMemo(
    () =>
      PROVIDER_PRESETS.flatMap((tier) =>
        tier.providers.map((item) => ({
          id: item.id,
          label: item.labelZh,
        })),
      ),
    [],
  );

  const apiKeyPlaceholder = useMemo(() => {
    if (['qwen', 'qwen-intl', 'qwen-us', 'dashscope', 'dashscope-intl', 'dashscope-us'].includes(provider)) {
      return 'Qwen 必填：DASHSCOPE_API_KEY';
    }
    if (['qwen-code', 'qwen-oauth'].includes(provider)) {
      return 'Qwen Code：QWEN_OAUTH_TOKEN（可选填）';
    }
    return '可选（建议填写，避免 provider 启动失败）';
  }, [provider]);

  const baseUrlPlaceholder = useMemo(() => {
    if (provider === 'qwen' || provider === 'qwen-intl' || provider === 'qwen-us') {
      return '可选，如 https://dashscope.aliyuncs.com/compatible-mode/v1';
    }
    return '可选，如 https://api.openai.com/v1';
  }, [provider]);

  const fetchConfiguredModels = async (showRefreshing = false) => {
    if (showRefreshing) setRefreshing(true);
    setLoading(!showRefreshing);
    try {
      const [configured, trial] = await Promise.all([loadConfiguredModels(), loadTrialModels()]);
      setConfiguredModels(configured);
      setTrialModels(trial);
    } catch {
      setConfiguredModels([]);
      setTrialModels([]);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const handleSave = async () => {
    if (!provider.trim() || !model.trim()) {
      setError('请先填写 provider 和 model');
      return;
    }
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      if (editingTarget) {
        await updateModelConfiguration(editingTarget, {
          provider,
          model,
          apiKey: apiKey.trim() || undefined,
          baseUrl: baseUrl.trim() || undefined,
          label: model.trim(),
        });
        setSuccess('模型信息已更新并同步到本地/远端配置');
      } else {
        await saveModelConfiguration({
          provider,
          model,
          apiKey: apiKey.trim() || undefined,
          baseUrl: baseUrl.trim() || undefined,
          label: model.trim(),
        });
        setSuccess('模型已写入远端配置并加入可切换列表');
      }
      setModel('');
      setApiKey('');
      setBaseUrl('');
      setEditingTarget(null);
      await fetchConfiguredModels();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : '保存失败');
    } finally {
      setSaving(false);
    }
  };

  const handleEdit = (configuredModel: ModelInfo) => {
    if (configuredModel.provider.startsWith('custom:')) {
      setProvider('custom');
      setBaseUrl(configuredModel.provider.slice('custom:'.length));
    } else {
      setProvider(configuredModel.provider);
      setBaseUrl(configuredModel.baseUrl ?? '');
    }
    setModel(configuredModel.value);
    setApiKey(configuredModel.apiKey ?? '');
    setEditingTarget({ provider: configuredModel.provider, model: configuredModel.value });
    setError(null);
    setSuccess(null);
    editorCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const cancelEdit = () => {
    setEditingTarget(null);
    setModel('');
    setApiKey('');
    setBaseUrl('');
  };

  const handleDelete = async (configuredModel: ModelInfo) => {
    setError(null);
    setSuccess(null);
    await deleteModelConfiguration({
      provider: configuredModel.provider,
      model: configuredModel.value,
    });
    setSuccess('模型已从可切换列表删除');
    await fetchConfiguredModels();
  };

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

  return (
    <div className="p-6 space-y-6 animate-fade-in">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <Cpu className="h-5 w-5" style={{ color: 'var(--pc-accent)' }} />
          <h2 className="text-sm font-semibold uppercase tracking-wider" style={{ color: 'var(--pc-text-primary)' }}>
            {t('modelswitch.title')} ({configuredModels.length})
          </h2>
        </div>
        <button
          type="button"
          onClick={() => void fetchConfiguredModels(true)}
          disabled={refreshing}
          className="btn-secondary flex items-center gap-2 px-3 py-1.5 text-xs rounded-[6px]"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />
          刷新
        </button>
      </div>

      <div ref={editorCardRef} className="card card-radius-6 p-5 space-y-4">
        <h3 className="text-[12px] font-semibold uppercase tracking-wider" style={{ color: 'var(--pc-text-faint)' }}>
          {editingTarget ? '编辑模型配置' : '新增模型配置'}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Provider</label>
            <select
              value={provider}
              onChange={(e) => setProvider(e.target.value)}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            >
              {providerOptions.map((item) => (
                <option key={item.id} value={item.id}>
                  {item.label} ({item.id})
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Model</label>
            <input
              value={model}
              onChange={(e) => setModel(e.target.value)}
              placeholder="例如 gpt-5.2 / qwen-plus / claude-sonnet-4-6"
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>API Key</label>
            <input
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              placeholder={apiKeyPlaceholder}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs" style={{ color: 'var(--pc-text-secondary)' }}>Base URL</label>
            <input
              value={baseUrl}
              onChange={(e) => setBaseUrl(e.target.value)}
              placeholder={baseUrlPlaceholder}
              className="w-full rounded-md border px-3 py-2 text-sm"
              style={{ borderColor: 'var(--pc-border)', background: 'var(--pc-bg-base)', color: 'var(--pc-text-primary)' }}
            />
          </div>
        </div>

        {success && <div className="text-sm" style={{ color: 'var(--color-status-success)' }}>{success}</div>}
        {error && <div className="text-sm" style={{ color: 'var(--color-status-error)' }}>{error}</div>}

        <div className="flex justify-end gap-2">
          {editingTarget && (
            <button
              type="button"
              onClick={cancelEdit}
              disabled={saving}
              className="btn-secondary px-4 py-2 text-sm rounded-[6px]"
            >
              取消编辑
            </button>
          )}
          <button
            type="button"
            onClick={() => void handleSave()}
            disabled={saving}
            className="btn-electric flex items-center gap-2 px-4 py-2 text-sm rounded-[6px]"
          >
            <Plus className="h-4 w-4" />
            {saving ? '保存中...' : editingTarget ? '保存编辑并同步配置' : '添加并写入远端配置'}
          </button>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-40">
          <div className="h-8 w-8 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--pc-border)', borderTopColor: 'var(--pc-accent)' }} />
        </div>
      ) : (
        <>
          <div>
            <h3 className="text-[10px] font-semibold uppercase tracking-wider mb-3" style={{ color: 'var(--pc-text-faint)' }}>
              {t('agent.model_selector_configured')} ({configuredModels.length})
            </h3>
            {configuredModels.length === 0 ? (
              <div className="card card-radius-6 p-5 text-sm" style={{ color: 'var(--pc-text-muted)' }}>
                {t('agent.model_selector_no_configured')}
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                {configuredModels.map((configuredModel) => (
                  <div key={`configured-${configuredModel.provider}-${configuredModel.value}`} className="card card-radius-6 p-5">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <h4 className="text-sm font-semibold truncate" style={{ color: 'var(--pc-text-primary)' }}>
                          {configuredModel.label}
                        </h4>
                        <p className="text-sm mt-1" style={{ color: 'var(--pc-text-muted)' }}>
                          {configuredModel.description ?? '当前配置模型'}
                        </p>
                        <p className="text-xs mt-1 font-mono" style={{ color: 'var(--pc-text-faint)' }}>
                          {configuredModel.provider}
                        </p>
                      </div>
                      <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-semibold border" style={{ color: 'var(--color-status-success)', borderColor: 'rgba(0,230,138,0.2)', background: 'rgba(0,230,138,0.06)' }}>
                        <Check className="h-3 w-3" />
                        {t('modelswitch.status_active')}
                      </span>
                    </div>
                  <div className="mt-3 flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => {
                        const key = `${configuredModel.provider}::${configuredModel.value}`;
                        setViewingModelKey((prev) => (prev === key ? null : key));
                      }}
                      className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                    >
                      <Eye className="h-3.5 w-3.5" />
                      查看
                    </button>
                    <button
                      type="button"
                      onClick={() => handleEdit(configuredModel)}
                      className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                    >
                      <Pencil className="h-3.5 w-3.5" />
                      编辑
                    </button>
                    <button
                      type="button"
                      onClick={() => void handleDelete(configuredModel)}
                      className="btn-secondary flex items-center gap-1 px-2.5 py-1 text-xs rounded-[6px]"
                      style={{ color: 'var(--color-status-error)' }}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                      删除
                    </button>
                  </div>
                  {viewingModelKey === `${configuredModel.provider}::${configuredModel.value}` && (
                    <div className="mt-3 text-xs space-y-1" style={{ color: 'var(--pc-text-secondary)' }}>
                      <div>Provider: <span className="font-mono">{configuredModel.provider}</span></div>
                      <div>Model: <span className="font-mono">{configuredModel.value}</span></div>
                      <div>Base URL: <span className="font-mono">{configuredModel.baseUrl || '未设置'}</span></div>
                      <div>API Key: <span className="font-mono">{configuredModel.apiKey || '未保存到本地'}</span></div>
                    </div>
                  )}
                  </div>
                ))}
              </div>
            )}
          </div>

          <div>
            <h3 className="text-[10px] font-semibold uppercase tracking-wider mb-3" style={{ color: 'var(--pc-text-faint)' }}>
              {t('agent.model_selector_trial')} ({trialModels.length})
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              {trialModels.map((trialModel) => (
                <div key={`trial-${trialModel.provider}-${trialModel.value}`} className="card card-radius-6 p-5">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <h4 className="text-sm font-semibold truncate" style={{ color: 'var(--pc-text-primary)' }}>
                        {trialModel.label}
                      </h4>
                      <p className="text-sm mt-1" style={{ color: 'var(--pc-text-muted)' }}>
                        {trialModel.description}
                      </p>
                      <p className="text-xs mt-1 font-mono" style={{ color: 'var(--pc-text-faint)' }}>
                        {trialModel.provider}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
