import { useState, useEffect, useCallback } from 'react';
import {
  listProviders, saveProvider, deleteProvider, healthCheckProvider, fetchProviderModels,
  listModels, saveModel, deleteModel,
  listRouting, saveRouting, deleteRouting,
} from '@/api/admin';
import type { ModelProvider, ModelConfig, RoutingRule } from '@/types/admin';

type TabId = 'providers' | 'models' | 'routing';

export function ModelsAdminPage() {
  const [tab, setTab] = useState<TabId>('providers');

  return (
    <div className="h-full flex flex-col bg-[#FFFAF5] dark:bg-[#1a1a2e]">
      {/* Header */}
      <div className="flex-shrink-0 px-6 py-4 border-b border-pink-100 dark:border-pink-900">
        <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-200">模型配置管理</h2>
        <p className="text-xs text-gray-400 mt-1">管理 LLM 供应商、模型和路由规则</p>
      </div>

      {/* Tabs */}
      <div className="flex-shrink-0 flex border-b border-pink-100 dark:border-pink-900 px-6">
        {([
          ['providers', '供应商'],
          ['models', '模型'],
          ['routing', '路由规则'],
        ] as [TabId, string][]).map(([id, label]) => (
          <button
            key={id}
            onClick={() => setTab(id)}
            className={`px-4 py-2.5 text-sm font-medium transition-colors border-b-2 -mb-px ${
              tab === id
                ? 'text-pink-500 border-pink-500'
                : 'text-gray-400 border-transparent hover:text-gray-600'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6">
        {tab === 'providers' && <ProvidersTab />}
        {tab === 'models' && <ModelsTab />}
        {tab === 'routing' && <RoutingTab />}
      </div>
    </div>
  );
}

// ========== Providers Tab ==========

function ProvidersTab() {
  const [providers, setProviders] = useState<ModelProvider[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editing, setEditing] = useState<{ name: string; base_url: string; api_key: string } | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [formName, setFormName] = useState('');
  const [formUrl, setFormUrl] = useState('');
  const [formKey, setFormKey] = useState('');
  const [saving, setSaving] = useState(false);
  const [healthMsg, setHealthMsg] = useState<Record<string, string>>({});

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const res = await listProviders();
    if (res.data?.providers) setProviders(res.data.providers);
    else if (res.error) setError(res.error);
    setLoading(false);
  }, []);

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

  const handleSave = async () => {
    if (!formName) return;
    setSaving(true);
    const res = await saveProvider(formName, formUrl, formKey);
    if (res.error) setError(res.error);
    else {
      setShowForm(false);
      setFormName(''); setFormUrl(''); setFormKey('');
      await load();
    }
    setSaving(false);
  };

  const handleDelete = async (name: string) => {
    if (!confirm(`确定要删除供应商 "${name}" 吗？`)) return;
    const res = await deleteProvider(name);
    if (res.error) setError(res.error);
    else await load();
  };

  const handleHealth = async (provider: string) => {
    setHealthMsg((p) => ({ ...p, [provider]: '检测中...' }));
    const res = await healthCheckProvider(provider);
    setHealthMsg((p) => ({ ...p, [provider]: res.data?.message || res.error || '未知结果' }));
  };

  const handleFetchModels = async (name: string, baseUrl: string) => {
    try {
      const res = await fetchProviderModels(name, baseUrl.replace(/\/+$/, '') + '/models');
      if (res.data) {
        alert(`获取到模型列表:\n${JSON.stringify(res.data, null, 2)}`);
      } else {
        alert('获取失败: ' + (res.error || '未知错误'));
      }
    } catch (err) {
      alert('获取失败: ' + (err instanceof Error ? err.message : '未知错误'));
    }
  };

  if (loading) return <div className="text-sm text-gray-400">加载中...</div>;

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-500">
          {error}
          <button onClick={() => setError('')} className="ml-2 text-red-400 hover:text-red-600">x</button>
        </div>
      )}

      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-400">{providers.length} 个供应商</span>
        <button
          onClick={() => { setShowForm(true); setEditing(null); setFormName(''); setFormUrl(''); setFormKey(''); }}
          className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 text-white rounded-lg transition-colors"
        >
          + 添加供应商
        </button>
      </div>

      {/* Add/Edit Form */}
      {(showForm || editing) && (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-200 dark:border-pink-800 space-y-3">
          <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">
            {editing ? `编辑 ${editing.name}` : '新供应商'}
          </h4>
          <input
            type="text" placeholder="名称 (如 openai)" value={formName}
            onChange={(e) => setFormName(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm"
            disabled={!!editing}
          />
          <input
            type="text" placeholder="Base URL (如 https://api.openai.com/v1)" value={formUrl}
            onChange={(e) => setFormUrl(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm"
          />
          <input
            type="password" placeholder="API Key" value={formKey}
            onChange={(e) => setFormKey(e.target.value)}
            className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm"
          />
          <div className="flex gap-2 justify-end">
            <button onClick={() => { setShowForm(false); setEditing(null); }}
              className="px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">
              取消
            </button>
            <button onClick={handleSave} disabled={saving || !formName}
              className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 disabled:bg-pink-300 text-white rounded-lg">
              {saving ? '保存中...' : '保存'}
            </button>
          </div>
        </div>
      )}

      {/* Provider List */}
      <div className="space-y-2">
        {providers.map((p) => (
          <div key={p.name} className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900">
            <div className="flex items-center justify-between">
              <div>
                <h5 className="text-sm font-medium text-gray-800 dark:text-gray-200">{p.name}</h5>
                <p className="text-xs text-gray-400 mt-0.5">{p.base_url}</p>
                <p className="text-xs text-gray-400">Key: {p.api_key ? p.api_key.slice(0, 8) + '...' : '(未设置)'}</p>
              </div>
              <div className="flex gap-1.5">
                <button onClick={() => handleFetchModels(p.name, p.base_url)}
                  className="px-2 py-1 text-xs text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors">
                  获取模型
                </button>
                <button onClick={() => handleHealth(p.name)}
                  className="px-2 py-1 text-xs text-green-500 hover:bg-green-50 dark:hover:bg-green-900/20 rounded transition-colors">
                  检测
                </button>
                <button onClick={() => { setEditing({ name: p.name, base_url: p.base_url, api_key: p.api_key }); setFormName(p.name); setFormUrl(p.base_url); setFormKey(p.api_key); }}
                  className="px-2 py-1 text-xs text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded transition-colors">
                  编辑
                </button>
                <button onClick={() => handleDelete(p.name)}
                  className="px-2 py-1 text-xs text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors">
                  删除
                </button>
              </div>
            </div>
            {healthMsg[p.name] && (
              <p className="mt-2 text-xs text-gray-500 bg-gray-50 dark:bg-gray-900 rounded p-2">{healthMsg[p.name]}</p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ========== Models Tab ==========

function ModelsTab() {
  const [models, setModels] = useState<ModelConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [editId, setEditId] = useState('');
  const [form, setForm] = useState({ id: '', name: '', provider: '', description: '', paramsJson: '{}' });
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const res = await listModels();
    if (res.data?.models) setModels(res.data.models);
    else if (res.error) setError(res.error);
    setLoading(false);
  }, []);

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

  const handleSave = async () => {
    if (!form.id || !form.provider) return;
    setSaving(true);
    let params: Record<string, unknown> | undefined;
    try { params = JSON.parse(form.paramsJson); } catch { params = undefined; }
    const res = await saveModel(form.id, {
      name: form.name, provider: form.provider, description: form.description, params,
    });
    if (res.error) setError(res.error);
    else { setShowForm(false); await load(); }
    setSaving(false);
  };

  const handleEdit = (m: ModelConfig) => {
    setEditId(m.id);
    setForm({ id: m.id, name: m.name, provider: m.provider, description: m.description || '', paramsJson: JSON.stringify(m.params || {}, null, 2) });
    setShowForm(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm(`确定要删除模型 "${id}" 吗？`)) return;
    const res = await deleteModel(id);
    if (res.error) setError(res.error);
    else await load();
  };

  if (loading) return <div className="text-sm text-gray-400">加载中...</div>;

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-500">
          {error}
          <button onClick={() => setError('')} className="ml-2 text-red-400 hover:text-red-600">x</button>
        </div>
      )}

      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-400">{models.length} 个模型</span>
        <button
          onClick={() => { setEditId(''); setForm({ id: '', name: '', provider: '', description: '', paramsJson: '{}' }); setShowForm(true); }}
          className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 text-white rounded-lg transition-colors"
        >
          + 添加模型
        </button>
      </div>

      {showForm && (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-200 dark:border-pink-800 space-y-3">
          <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">{editId ? `编辑 ${editId}` : '新模型'}</h4>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-gray-400">ID</label>
              <input type="text" placeholder="如 gpt-4o" value={form.id}
                onChange={(e) => setForm({ ...form, id: e.target.value })}
                disabled={!!editId}
                className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
            </div>
            <div>
              <label className="text-xs text-gray-400">名称</label>
              <input type="text" placeholder="显示名称" value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
            </div>
          </div>
          <div>
            <label className="text-xs text-gray-400">供应商</label>
            <input type="text" placeholder="如 openai" value={form.provider}
              onChange={(e) => setForm({ ...form, provider: e.target.value })}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
          </div>
          <div>
            <label className="text-xs text-gray-400">描述</label>
            <input type="text" value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
          </div>
          <div>
            <label className="text-xs text-gray-400">参数 (JSON)</label>
            <textarea rows={4} value={form.paramsJson}
              onChange={(e) => setForm({ ...form, paramsJson: e.target.value })}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1 font-mono" />
          </div>
          <div className="flex gap-2 justify-end">
            <button onClick={() => setShowForm(false)}
              className="px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">取消</button>
            <button onClick={handleSave} disabled={saving || !form.id}
              className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 disabled:bg-pink-300 text-white rounded-lg">
              {saving ? '保存中...' : '保存'}
            </button>
          </div>
        </div>
      )}

      <div className="space-y-2">
        {models.map((m) => (
          <div key={m.id} className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900">
            <div className="flex items-center justify-between">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <h5 className="text-sm font-medium text-gray-800 dark:text-gray-200">{m.id}</h5>
                  {m.enabled === false && (
                    <span className="px-1.5 py-0.5 text-[10px] bg-red-100 text-red-500 rounded">禁用</span>
                  )}
                  {m.tags && m.tags.length > 0 && m.tags.map((t) => (
                    <span key={t} className="px-1.5 py-0.5 text-[10px] bg-blue-100 text-blue-500 rounded">{t}</span>
                  ))}
                </div>
                <p className="text-xs text-gray-400 mt-0.5">
                  {m.name} · {m.provider} · 优先级 {m.priority ?? '-'}
                  {m.description ? ` · ${m.description}` : ''}
                </p>
              </div>
              <div className="flex gap-1.5 ml-3">
                <button onClick={() => handleEdit(m)}
                  className="px-2 py-1 text-xs text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded transition-colors">编辑</button>
                <button onClick={() => handleDelete(m.id)}
                  className="px-2 py-1 text-xs text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors">删除</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ========== Routing Tab ==========

function RoutingTab() {
  const [rules, setRules] = useState<RoutingRule[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [formPurpose, setFormPurpose] = useState('');
  const [formChain, setFormChain] = useState('');
  const [formRequired, setFormRequired] = useState(false);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    const res = await listRouting();
    if (res.data) {
      // Response may wrap rules in an object or be the array directly
      const data = res.data as unknown as { rules?: RoutingRule[] } | RoutingRule[];
      if (Array.isArray(data)) setRules(data);
      else if (data?.rules) setRules(data.rules);
    } else if (res.error) setError(res.error);
    setLoading(false);
  }, []);

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

  const handleSave = async () => {
    if (!formPurpose || !formChain.trim()) return;
    setSaving(true);
    const chain = formChain.split(',').map((s) => s.trim()).filter(Boolean);
    const res = await saveRouting(formPurpose, chain, formRequired);
    if (res.error) setError(res.error);
    else { setShowForm(false); setFormPurpose(''); setFormChain(''); await load(); }
    setSaving(false);
  };

  const handleDelete = async (purpose: string) => {
    if (!confirm(`确定要删除路由规则 "${purpose}" 吗？`)) return;
    const res = await deleteRouting(purpose);
    if (res.error) setError(res.error);
    else await load();
  };

  if (loading) return <div className="text-sm text-gray-400">加载中...</div>;

  return (
    <div className="space-y-4">
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-500">
          {error}
          <button onClick={() => setError('')} className="ml-2 text-red-400 hover:text-red-600">x</button>
        </div>
      )}

      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-400">{rules.length} 条规则</span>
        <button
          onClick={() => { setShowForm(true); setFormPurpose(''); setFormChain(''); setFormRequired(false); }}
          className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 text-white rounded-lg transition-colors"
        >
          + 添加规则
        </button>
      </div>

      {showForm && (
        <div className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-200 dark:border-pink-800 space-y-3">
          <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300">新路由规则</h4>
          <div>
            <label className="text-xs text-gray-400">Purpose</label>
            <input type="text" placeholder="如 chat, deep_thinking, vision..." value={formPurpose}
              onChange={(e) => setFormPurpose(e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
          </div>
          <div>
            <label className="text-xs text-gray-400">Fallback Chain (逗号分隔)</label>
            <input type="text" placeholder="如 gpt-4o, gpt-4o-mini, claude-sonnet-4-6" value={formChain}
              onChange={(e) => setFormChain(e.target.value)}
              className="w-full px-3 py-2 rounded-lg border border-pink-200 dark:border-pink-700 bg-white dark:bg-gray-700 text-sm mt-1" />
          </div>
          <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
            <input type="checkbox" checked={formRequired} onChange={(e) => setFormRequired(e.target.checked)}
              className="rounded border-pink-300 text-pink-500 focus:ring-pink-400" />
            必须匹配
          </label>
          <div className="flex gap-2 justify-end">
            <button onClick={() => setShowForm(false)}
              className="px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">取消</button>
            <button onClick={handleSave} disabled={saving || !formPurpose}
              className="px-3 py-1.5 text-xs font-medium bg-pink-400 hover:bg-pink-500 disabled:bg-pink-300 text-white rounded-lg">
              {saving ? '保存中...' : '保存'}
            </button>
          </div>
        </div>
      )}

      <div className="space-y-2">
        {rules.map((r) => (
          <div key={r.purpose} className="p-4 bg-white dark:bg-gray-800 rounded-xl border border-pink-100 dark:border-pink-900">
            <div className="flex items-center justify-between">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <h5 className="text-sm font-medium text-gray-800 dark:text-gray-200 font-mono">{r.purpose}</h5>
                  {r.required && (
                    <span className="px-1.5 py-0.5 text-[10px] bg-amber-100 text-amber-600 rounded">必须</span>
                  )}
                </div>
                <div className="flex flex-wrap gap-1 mt-1.5">
                  {r.fallback_chain.map((m, i) => (
                    <span key={m} className="px-2 py-0.5 text-[10px] bg-pink-50 dark:bg-pink-900/20 text-pink-600 dark:text-pink-400 rounded-full">
                      {i === 0 ? '★ ' : ''}{m}
                    </span>
                  ))}
                </div>
              </div>
              <button onClick={() => handleDelete(r.purpose)}
                className="px-2 py-1 text-xs text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors ml-3">删除</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
