import { useEffect, useState } from 'react';
import { App as AntApp, Form } from 'antd';
import type { LLMProvider } from '../../api';
import { LLMProviderAPI } from '../../api';
import ProvidersHero from './components/ProvidersHero';
import ProviderGrid from './components/ProviderGrid';
import ProviderEditorModal from './components/ProviderEditorModal';

export default function LLMProvidersPage() {
  const { message } = AntApp.useApp();
  const [list, setList] = useState<LLMProvider[]>([]);
  const [editorOpen, setEditorOpen] = useState(false);
  const [editing, setEditing] = useState<LLMProvider | null>(null);
  const [form] = Form.useForm();
  const [testing, setTesting] = useState<string | null>(null);

  const load = async () => {
    try {
      setList(await LLMProviderAPI.list());
    } catch (e: any) {
      message.error('加载失败：' + (e?.message ?? e));
    }
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const openCreate = () => {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ kind: 'openai', enabled: true });
    setEditorOpen(true);
  };

  const openEdit = (p: LLMProvider) => {
    setEditing(p);
    form.setFieldsValue({
      name: p.name,
      kind: p.kind,
      baseUrl: p.baseUrl,
      models: p.models?.join(', ') || '',
      defaultModel: p.defaultModel,
      enabled: p.enabled,
      isDefault: p.isDefault
    });
    setEditorOpen(true);
  };

  const onSave = async () => {
    const v = await form.validateFields();
    const payload = {
      ...v,
      models: typeof v.models === 'string' ? v.models.split(/[,，]/).map((s: string) => s.trim()).filter(Boolean) : v.models
    };
    try {
      if (editing) {
        await LLMProviderAPI.update(editing.id, payload);
        message.success('已更新');
      } else {
        await LLMProviderAPI.create(payload);
        message.success('已创建');
      }
      setEditorOpen(false);
      load();
    } catch (e: any) {
      message.error('保存失败：' + (e?.response?.data?.error ?? e?.message ?? e));
    }
  };

  const onDelete = async (p: LLMProvider) => {
    await LLMProviderAPI.remove(p.id);
    message.success('已删除');
    load();
  };

  const onTest = async (p: LLMProvider) => {
    setTesting(p.id);
    try {
      const r = await LLMProviderAPI.test(p.id, p.defaultModel);
      if (r.ok) {
        message.success(`✅ 连通：${r.model} · 用量 ${(r as any).usage?.TotalTokens ?? '?'} tokens`);
      } else {
        message.error('❌ 失败：' + (r.error || 'unknown'));
      }
    } catch (e: any) {
      message.error('测试失败：' + (e?.response?.data?.error ?? e?.message ?? e));
    } finally {
      setTesting(null);
    }
  };

  const onSetDefault = async (p: LLMProvider) => {
    await LLMProviderAPI.setDefault(p.id);
    message.success('已设为默认');
    load();
  };

  return (
    <div className="page-container" style={{ maxWidth: 1080 }}>
      <ProvidersHero list={list} onAdd={openCreate} />
      <ProviderGrid list={list} testingId={testing} onTest={onTest} onSetDefault={onSetDefault} onEdit={openEdit} onDelete={onDelete} />
      <ProviderEditorModal open={editorOpen} editing={editing} form={form} onCancel={() => setEditorOpen(false)} onOk={onSave} />
    </div>
  );
}

