import { useEffect, useState } from 'react';
import {
  fetchLlmKeys,
  fetchLlmGlobal,
  createLlmKey,
  patchLlmKey,
  deleteLlmKey,
  selectLlmKey,
  testLlmKey,
  putLlmGlobal,
  syncLlmProviders,
  type LlmKey,
} from '../../api/admin';

export function LlmPage() {
  const [keys, setKeys] = useState<LlmKey[]>([]);
  const [globalModel, setGlobalModel] = useState<string>('');
  const [globalModelInput, setGlobalModelInput] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [testResults, setTestResults] = useState<Record<string, { ok: boolean; msg: string }>>({});
  const [showCreate, setShowCreate] = useState(false);
  const [editKey, setEditKey] = useState<LlmKey | null>(null);

  const load = async () => {
    setError(null);
    try {
      const [keysResult, globalResult] = await Promise.all([fetchLlmKeys(), fetchLlmGlobal()]);
      setKeys(keysResult.keys);
      const model = globalResult.settings?.model ?? '';
      setGlobalModel(model);
      setGlobalModelInput(model);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    }
  };

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

  const handleSelect = async (keyId: string) => {
    setBusy(true);
    try {
      await selectLlmKey(keyId);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async (key: LlmKey) => {
    if (!window.confirm(`确认删除密钥「${key.name}」？`)) return;
    setBusy(true);
    try {
      await deleteLlmKey(key.id);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setBusy(false);
    }
  };

  const handleTest = async (key: LlmKey) => {
    setTestResults((prev) => ({ ...prev, [key.id]: { ok: false, msg: '测试中…' } }));
    try {
      const result = await testLlmKey(key.id);
      setTestResults((prev) => ({
        ...prev,
        [key.id]: { ok: result.ok, msg: result.ok ? `OK (${result.model ?? ''})` : (result.error ?? '失败') },
      }));
    } catch (err) {
      setTestResults((prev) => ({
        ...prev,
        [key.id]: { ok: false, msg: err instanceof Error ? err.message : '连接失败' },
      }));
    }
  };

  const handleSaveGlobal = async () => {
    setBusy(true);
    try {
      await putLlmGlobal(globalModelInput.trim());
      setGlobalModel(globalModelInput.trim());
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败');
    } finally {
      setBusy(false);
    }
  };

  const handleSync = async () => {
    setBusy(true);
    try {
      const result = await syncLlmProviders();
      alert(`同步完成，更新 ${result.synced} 条`);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : '同步失败');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="grid">
      {error ? <p className="alert">{error}</p> : null}

      {/* Global model */}
      <div className="card grid">
        <h3 style={{ margin: 0 }}>全局模型设置</h3>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <input
            value={globalModelInput}
            onChange={(e) => setGlobalModelInput(e.target.value)}
            placeholder="如 deepseek-chat"
            style={{ flex: '1 1 200px', padding: '8px 12px', borderRadius: 999, border: '1px solid #d6d0c3' }}
          />
          <button type="button" className="btn" onClick={() => void handleSaveGlobal()} disabled={busy || globalModelInput === globalModel}>
            保存
          </button>
        </div>
        {globalModel ? (
          <p style={{ fontSize: 12, color: '#68716c', margin: 0 }}>当前：{globalModel}</p>
        ) : (
          <p style={{ fontSize: 12, color: '#68716c', margin: 0 }}>未设置（使用选中密钥自带的 model）</p>
        )}
      </div>

      {/* Keys list */}
      <div className="card grid">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ margin: 0 }}>API 密钥（{keys.length}）</h3>
          <div style={{ display: 'flex', gap: 8 }}>
            <button type="button" className="btn secondary" onClick={() => void handleSync()} disabled={busy}>
              同步 Providers
            </button>
            <button type="button" className="btn" onClick={() => setShowCreate(true)}>
              添加密钥
            </button>
          </div>
        </div>

        {keys.length === 0 ? (
          <p style={{ color: '#68716c' }}>暂无配置密钥</p>
        ) : (
          keys.map((key) => (
            <div
              key={key.id}
              style={{
                border: `1px solid ${key.isSelected ? '#2f6f57' : '#d6d0c3'}`,
                borderRadius: 12,
                padding: 12,
                background: key.isSelected ? '#f0f9f4' : undefined,
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
                <div>
                  <strong>{key.name}</strong>
                  {key.isSelected ? (
                    <span style={{ marginLeft: 8, fontSize: 11, color: '#2f6f57', fontWeight: 600 }}>✓ 当前选中</span>
                  ) : null}
                  <p style={{ margin: '4px 0 0', fontSize: 12, color: '#68716c' }}>
                    {key.provider} {key.model ? `· ${key.model}` : ''}
                    {key.models?.length ? ` · ${key.models.join(', ')}` : ''}
                  </p>
                </div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {!key.isSelected ? (
                    <button
                      type="button"
                      className="btn"
                      style={{ padding: '4px 10px', fontSize: 12 }}
                      onClick={() => void handleSelect(key.id)}
                      disabled={busy}
                    >
                      选为当前
                    </button>
                  ) : null}
                  <button
                    type="button"
                    className="btn secondary"
                    style={{ padding: '4px 10px', fontSize: 12 }}
                    onClick={() => void handleTest(key)}
                  >
                    测试
                  </button>
                  <button
                    type="button"
                    className="btn secondary"
                    style={{ padding: '4px 10px', fontSize: 12 }}
                    onClick={() => setEditKey(key)}
                  >
                    编辑
                  </button>
                  <button
                    type="button"
                    className="btn danger"
                    style={{ padding: '4px 10px', fontSize: 12 }}
                    onClick={() => void handleDelete(key)}
                    disabled={busy}
                  >
                    删除
                  </button>
                </div>
              </div>
              {testResults[key.id] ? (
                <p
                  style={{
                    margin: '8px 0 0',
                    fontSize: 12,
                    color: testResults[key.id].ok ? '#2f6f57' : '#b42318',
                  }}
                >
                  {testResults[key.id].msg}
                </p>
              ) : null}
            </div>
          ))
        )}
      </div>

      {showCreate ? (
        <CreateKeyModal
          onClose={() => setShowCreate(false)}
          onSuccess={() => { setShowCreate(false); void load(); }}
        />
      ) : null}

      {editKey ? (
        <EditKeyModal
          llmKey={editKey}
          onClose={() => setEditKey(null)}
          onSuccess={() => { setEditKey(null); void load(); }}
        />
      ) : null}
    </div>
  );
}

function CreateKeyModal({ onClose, onSuccess }: { onClose: () => void; onSuccess: () => void }) {
  const [name, setName] = useState('');
  const [provider, setProvider] = useState('openai');
  const [apiKey, setApiKey] = useState('');
  const [model, setModel] = useState('');
  const [baseUrl, setBaseUrl] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async () => {
    if (!name.trim() || !apiKey.trim()) { setError('名称和 API Key 必填'); return; }
    setBusy(true);
    try {
      await createLlmKey({ name: name.trim(), provider, apiKey, model: model.trim() || undefined, baseUrl: baseUrl.trim() || undefined });
      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : '创建失败');
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal title="添加 API 密钥" onClose={onClose}>
      <div className="grid">
        <LlmField label="名称"><input value={name} onChange={(e) => setName(e.target.value)} placeholder="DeepSeek Default" /></LlmField>
        <LlmField label="Provider">
          <select value={provider} onChange={(e) => setProvider(e.target.value)}>
            <option value="openai">openai</option>
            <option value="deepseek">deepseek</option>
            <option value="anthropic">anthropic</option>
            <option value="ollama">ollama</option>
            <option value="openrouter">openrouter</option>
          </select>
        </LlmField>
        <LlmField label="API Key"><input value={apiKey} onChange={(e) => setApiKey(e.target.value)} type="password" placeholder="sk-..." /></LlmField>
        <LlmField label="默认模型（可选）"><input value={model} onChange={(e) => setModel(e.target.value)} placeholder="deepseek-chat" /></LlmField>
        <LlmField label="Base URL（可选）"><input value={baseUrl} onChange={(e) => setBaseUrl(e.target.value)} placeholder="https://api.deepseek.com/v1" /></LlmField>
        {error ? <p className="alert">{error}</p> : null}
        <ModalActions onClose={onClose} onSubmit={() => void handleSubmit()} busy={busy} />
      </div>
    </Modal>
  );
}

function EditKeyModal({ llmKey, onClose, onSuccess }: { llmKey: LlmKey; onClose: () => void; onSuccess: () => void }) {
  const [name, setName] = useState(llmKey.name);
  const [apiKey, setApiKey] = useState('');
  const [model, setModel] = useState(llmKey.model ?? '');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async () => {
    setBusy(true);
    try {
      const patch: Record<string, string> = {};
      if (name !== llmKey.name) patch.name = name.trim();
      if (apiKey) patch.apiKey = apiKey;
      if (model !== (llmKey.model ?? '')) patch.model = model.trim();
      if (Object.keys(patch).length === 0) { onClose(); return; }
      await patchLlmKey(llmKey.id, patch);
      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新失败');
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal title={`编辑：${llmKey.name}`} onClose={onClose}>
      <div className="grid">
        <LlmField label="名称"><input value={name} onChange={(e) => setName(e.target.value)} /></LlmField>
        <LlmField label="新 API Key（留空不修改）"><input value={apiKey} onChange={(e) => setApiKey(e.target.value)} type="password" placeholder="留空不修改" /></LlmField>
        <LlmField label="默认模型"><input value={model} onChange={(e) => setModel(e.target.value)} /></LlmField>
        {error ? <p className="alert">{error}</p> : null}
        <ModalActions onClose={onClose} onSubmit={() => void handleSubmit()} busy={busy} />
      </div>
    </Modal>
  );
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.35)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="card grid" style={{ width: '100%', maxWidth: 480, margin: 16, maxHeight: '90vh', overflowY: 'auto' }}>
        <h3 style={{ margin: 0 }}>{title}</h3>
        {children}
      </div>
    </div>
  );
}

function LlmField({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ display: 'grid', gap: 4 }}>
      <label style={{ fontSize: 12, color: '#68716c' }}>{label}</label>
      {children}
    </div>
  );
}

function ModalActions({ onClose, onSubmit, busy }: { onClose: () => void; onSubmit: () => void; busy: boolean }) {
  return (
    <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
      <button type="button" className="btn secondary" onClick={onClose} disabled={busy}>取消</button>
      <button type="button" className="btn" onClick={onSubmit} disabled={busy}>{busy ? '处理中…' : '确认'}</button>
    </div>
  );
}
