import { ApiOutlined, CheckCircleOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { App, Button, Form, Input, InputNumber, Modal, Space, Switch, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useMemo, useState } from 'react';

import { initialProviders, type ProviderItem } from './mock';

interface ProviderFormValues {
  name: string;
  baseUrl: string;
  modelCount: number;
  apiKey?: string;
}

export default function LLMProviders() {
  const { message } = App.useApp();
  const [form] = Form.useForm<ProviderFormValues>();
  const [providers, setProviders] = useState(initialProviders);
  const [keyword, setKeyword] = useState('');
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<ProviderItem>();

  const filteredProviders = useMemo(() => {
    const normalized = keyword.trim().toLowerCase();
    if (!normalized) return providers;
    return providers.filter(item => item.name.toLowerCase().includes(normalized));
  }, [keyword, providers]);

  const openCreate = () => {
    setEditing(undefined);
    form.setFieldsValue({ name: '', baseUrl: '', modelCount: 0, apiKey: '' });
    setFormOpen(true);
  };

  const openEditCredential = (record: ProviderItem) => {
    setEditing(record);
    form.setFieldsValue({ name: record.name, baseUrl: record.baseUrl, modelCount: record.modelCount, apiKey: '' });
    setFormOpen(true);
  };

  const saveProvider = async () => {
    const values = await form.validateFields();
    if (editing) {
      setProviders(current =>
        current.map(item =>
          item.id === editing.id
            ? {
                ...item,
                name: values.name,
                baseUrl: values.baseUrl,
                modelCount: values.modelCount,
                credential: values.apiKey ? '已配置' : item.credential,
              }
            : item,
        ),
      );
      message.success('供应商已更新');
    } else {
      setProviders(current => [
        ...current,
        {
          id: `provider-${Date.now()}`,
          name: values.name,
          baseUrl: values.baseUrl,
          modelCount: values.modelCount,
          credential: values.apiKey ? '已配置' : '未配置',
          enabled: true,
        },
      ]);
      message.success('供应商已添加');
    }
    setFormOpen(false);
    form.resetFields();
  };

  const testConnection = (record: ProviderItem) => {
    if (record.credential === '未配置') {
      message.warning(`${record.name} 尚未配置凭证`);
      return;
    }
    message.success(`${record.name} 连通正常`);
  };

  const columns: ColumnsType<ProviderItem> = [
    {
      title: '供应商',
      dataIndex: 'name',
      width: 200,
      render: (value: string) => (
        <Space>
          <ApiOutlined style={{ color: '#1677ff' }} />
          <Typography.Text strong>{value}</Typography.Text>
        </Space>
      ),
    },
    { title: 'Base URL', dataIndex: 'baseUrl', ellipsis: true },
    { title: '关联模型数', dataIndex: 'modelCount', width: 120, align: 'right' },
    {
      title: '凭证状态',
      dataIndex: 'credential',
      width: 120,
      render: (value: ProviderItem['credential']) => (
        <Tag color={value === '已配置' ? 'success' : 'warning'}>{value}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      width: 100,
      render: (value: boolean, record) => (
        <Switch
          size="small"
          checked={value}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          aria-label={`${record.name}状态`}
          onChange={checked => {
            setProviders(current =>
              current.map(item => (item.id === record.id ? { ...item, enabled: checked } : item)),
            );
            message.success(checked ? '供应商已启用' : '供应商已禁用');
          }}
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 220,
      render: (_, record) => (
        <Space size={4}>
          <Button type="link" size="small" onClick={() => openEditCredential(record)}>
            编辑凭证
          </Button>
          <Button type="link" size="small" icon={<CheckCircleOutlined />} onClick={() => testConnection(record)}>
            测试连通
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <ProCard variant="outlined">
      <Space vertical size={16} style={{ width: '100%' }}>
        <Space style={{ width: '100%', justifyContent: 'space-between' }} align="start">
          <div>
            <Typography.Title level={5} style={{ margin: 0 }}>
              供应商管理
            </Typography.Title>
            <Typography.Text type="secondary">
              管理接入的大模型供应商，配置凭证信息，测试连通性并启用或禁用。
            </Typography.Text>
          </div>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            新增供应商
          </Button>
        </Space>

        <Input
          allowClear
          prefix={<SearchOutlined />}
          placeholder="搜索供应商名称"
          style={{ width: 260 }}
          value={keyword}
          onChange={event => setKeyword(event.target.value)}
        />

        <Table<ProviderItem>
          rowKey="id"
          columns={columns}
          dataSource={filteredProviders}
          scroll={{ x: 900 }}
          pagination={{ pageSize: 10, showSizeChanger: true, showTotal: total => `共 ${total} 条` }}
        />
      </Space>

      <Modal
        open={formOpen}
        title={editing ? '编辑供应商' : '新增供应商'}
        okText="保存"
        cancelText="取消"
        onOk={saveProvider}
        onCancel={() => setFormOpen(false)}
      >
        <Form<ProviderFormValues> form={form} layout="vertical" requiredMark="optional">
          <Form.Item label="供应商名称" name="name" rules={[{ required: true, message: '请输入供应商名称' }]}>
            <Input placeholder="例如 OpenAI" />
          </Form.Item>
          <Form.Item label="Base URL" name="baseUrl" rules={[{ required: true, message: '请输入 Base URL' }]}>
            <Input placeholder="例如 https://api.openai.com/v1" />
          </Form.Item>
          <Form.Item label="关联模型数" name="modelCount">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item label="API Key" name="apiKey" extra="留空则不修改现有凭证">
            <Input.Password placeholder="请输入 API Key" />
          </Form.Item>
        </Form>
      </Modal>
    </ProCard>
  );
}
