import { DeleteOutlined, EditOutlined, HolderOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { Line } from '@ant-design/charts';
import { ProCard } from '@ant-design/pro-components';
import {
  App,
  Button,
  Col,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tag,
  Typography,
  theme,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useMemo, useState } from 'react';

import {
  initialModels,
  recentCalls,
  usageTrend,
  type ModelItem,
  type ModelProvider,
  type ModelType,
  type RecentCall,
} from './mock';

interface ModelFormValues {
  name: string;
  provider: ModelProvider;
  modelId: string;
  type: ModelType;
  order: number;
  enabled: boolean;
}

const providerOptions: ModelProvider[] = ['OpenAI', 'Anthropic', '阿里云百炼', 'Google', 'DeepSeek'];
const typeOptions: ModelType[] = ['对话', '嵌入', '多模态'];

const normalizeOrder = (items: ModelItem[]) => items.map((item, index) => ({ ...item, order: index + 1 }));

export default function LLM() {
  const { message } = App.useApp();
  const { token } = theme.useToken();
  const [form] = Form.useForm<ModelFormValues>();
  const [models, setModels] = useState(initialModels);
  const [keyword, setKeyword] = useState('');
  const [provider, setProvider] = useState<ModelProvider>();
  const [enabled, setEnabled] = useState<boolean>();
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [editingModel, setEditingModel] = useState<ModelItem>();
  const [formOpen, setFormOpen] = useState(false);
  const [usageModel, setUsageModel] = useState<ModelItem>();
  const [draggingId, setDraggingId] = useState<string>();

  const filteredModels = useMemo(() => {
    const normalizedKeyword = keyword.trim().toLowerCase();
    return models.filter(item => {
      const matchesKeyword =
        !normalizedKeyword ||
        item.name.toLowerCase().includes(normalizedKeyword) ||
        item.modelId.toLowerCase().includes(normalizedKeyword);
      return (
        matchesKeyword &&
        (!provider || item.provider === provider) &&
        (enabled === undefined || item.enabled === enabled)
      );
    });
  }, [enabled, keyword, models, provider]);

  const openCreate = () => {
    setEditingModel(undefined);
    form.setFieldsValue({
      name: '',
      provider: 'OpenAI',
      modelId: '',
      type: '对话',
      order: models.length + 1,
      enabled: true,
    });
    setFormOpen(true);
  };

  const openEdit = (record: ModelItem) => {
    setEditingModel(record);
    form.setFieldsValue(record);
    setFormOpen(true);
  };

  const saveModel = async () => {
    const values = await form.validateFields();
    if (editingModel) {
      const updated = models.map(item => (item.id === editingModel.id ? { ...item, ...values } : item));
      const target = updated.find(item => item.id === editingModel.id)!;
      const withoutTarget = updated.filter(item => item.id !== editingModel.id);
      withoutTarget.splice(Math.max(0, values.order - 1), 0, target);
      setModels(normalizeOrder(withoutTarget));
      message.success('模型已更新');
    } else {
      const newModel: ModelItem = {
        ...values,
        id: `model-${Date.now()}`,
        todayToken: 0,
        updatedAt: '2026-07-26 00:00:00',
      };
      const next = [...models];
      next.splice(Math.max(0, values.order - 1), 0, newModel);
      setModels(normalizeOrder(next));
      message.success('模型已添加');
    }
    setFormOpen(false);
    form.resetFields();
  };

  const deleteModels = (ids: React.Key[]) => {
    setModels(current => normalizeOrder(current.filter(item => !ids.includes(item.id))));
    setSelectedKeys([]);
    message.success(`已删除 ${ids.length} 个模型`);
  };

  const changeOrder = (record: ModelItem, nextOrder: number | null) => {
    if (!nextOrder) return;
    const withoutCurrent = models.filter(item => item.id !== record.id);
    withoutCurrent.splice(Math.min(Math.max(nextOrder - 1, 0), withoutCurrent.length), 0, record);
    setModels(normalizeOrder(withoutCurrent));
  };

  const dropModel = (targetId: string) => {
    if (!draggingId || draggingId === targetId) return;
    const source = models.find(item => item.id === draggingId);
    const targetIndex = models.findIndex(item => item.id === targetId);
    if (!source || targetIndex < 0) return;
    const next = models.filter(item => item.id !== draggingId);
    next.splice(targetIndex, 0, source);
    setModels(normalizeOrder(next));
    setDraggingId(undefined);
    message.success('排序已更新');
  };

  const columns: ColumnsType<ModelItem> = [
    {
      title: '',
      key: 'drag',
      width: 48,
      align: 'center',
      render: (_, record) => (
        <Button
          type="text"
          aria-label={`拖动排序-${record.name}`}
          icon={<HolderOutlined />}
          style={{ cursor: 'grab', color: token.colorTextTertiary }}
        />
      ),
    },
    { title: '模型名称', dataIndex: 'name', width: 170, ellipsis: true },
    {
      title: '供应商',
      dataIndex: 'provider',
      width: 130,
      render: (value: ModelProvider) => <Tag color="blue">{value}</Tag>,
    },
    { title: '模型 ID', dataIndex: 'modelId', width: 220, ellipsis: true },
    {
      title: '类型',
      dataIndex: 'type',
      width: 90,
      render: (value: ModelType) => <Tag>{value}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      width: 100,
      render: (value: boolean, record) => (
        <Switch
          size="small"
          checked={value}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          aria-label={`${record.name}状态`}
          onChange={checked => {
            setModels(current => current.map(item => (item.id === record.id ? { ...item, enabled: checked } : item)));
            message.success(checked ? '模型已启用' : '模型已禁用');
          }}
        />
      ),
    },
    {
      title: '今日 Token',
      dataIndex: 'todayToken',
      width: 130,
      align: 'right',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: '排序',
      dataIndex: 'order',
      width: 82,
      render: (value: number, record) => (
        <InputNumber
          aria-label={`${record.name}排序`}
          size="small"
          min={1}
          max={models.length}
          value={value}
          controls={false}
          style={{ width: 48 }}
          onChange={next => changeOrder(record, next)}
        />
      ),
    },
    { title: '更新时间', dataIndex: 'updatedAt', width: 170 },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size={4}>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" onClick={() => setUsageModel(record)}>
            用量
          </Button>
          <Popconfirm title={`确定删除 ${record.name}？`} onConfirm={() => deleteModels([record.id])}>
            <Button type="link" danger size="small" icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const recentColumns: ColumnsType<RecentCall> = [
    { title: '时间', dataIndex: 'time' },
    { title: 'Token', dataIndex: 'token', align: 'right', render: (value: number) => value.toLocaleString() },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (value: RecentCall['status']) => <Tag color={value === '成功' ? 'success' : 'error'}>{value}</Tag>,
    },
  ];

  const usageLineConfig = {
    data: usageTrend,
    xField: 'date',
    yField: 'value',
    height: 210,
    shapeField: 'smooth',
    style: { stroke: token.colorPrimary, lineWidth: 2 },
    area: {
      style: {
        fill: `linear-gradient(-90deg, ${token.colorPrimary}00 0%, ${token.colorPrimary}38 100%)`,
      },
    },
    point: { sizeField: 3, shapeField: 'circle', style: { fill: token.colorPrimary } },
    axis: {
      y: { labelFormatter: (value: number) => `${Math.round(value / 1000000)}M` },
    },
  };

  return (
    <>
      <ProCard variant="outlined">
        <Space vertical size={16} style={{ width: '100%' }}>
          <Row gutter={[12, 12]} justify="space-between">
            <Col flex="auto">
              <Space wrap>
                <Input
                  allowClear
                  prefix={<SearchOutlined />}
                  placeholder="搜索模型名称或 ID"
                  style={{ width: 240 }}
                  value={keyword}
                  onChange={event => setKeyword(event.target.value)}
                />
                <Select
                  allowClear
                  placeholder="全部供应商"
                  style={{ width: 160 }}
                  options={providerOptions.map(value => ({ label: value, value }))}
                  value={provider}
                  onChange={setProvider}
                />
                <Select
                  allowClear
                  placeholder="全部状态"
                  style={{ width: 130 }}
                  options={[
                    { label: '已启用', value: true },
                    { label: '已禁用', value: false },
                  ]}
                  value={enabled}
                  onChange={setEnabled}
                />
              </Space>
            </Col>
            <Col>
              <Space>
                <Popconfirm
                  title={`确定删除选中的 ${selectedKeys.length} 个模型？`}
                  disabled={!selectedKeys.length}
                  onConfirm={() => deleteModels(selectedKeys)}
                >
                  <Button danger disabled={!selectedKeys.length}>
                    批量删除
                  </Button>
                </Popconfirm>
                <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
                  新增模型
                </Button>
              </Space>
            </Col>
          </Row>

          <Table<ModelItem>
            rowKey="id"
            columns={columns}
            dataSource={filteredModels}
            rowSelection={{ selectedRowKeys: selectedKeys, onChange: setSelectedKeys }}
            onRow={record => ({
              draggable: true,
              onDragStart: () => setDraggingId(record.id),
              onDragOver: event => event.preventDefault(),
              onDrop: () => dropModel(record.id),
            })}
            scroll={{ x: 1400 }}
            pagination={{ pageSize: 10, showSizeChanger: true, showTotal: total => `共 ${total} 条` }}
          />
        </Space>
      </ProCard>

      <Modal
        open={formOpen}
        title={editingModel ? '编辑模型' : '新增模型'}
        okText="保存"
        cancelText="取消"
        width={680}
        onOk={saveModel}
        onCancel={() => setFormOpen(false)}
      >
        <Form<ModelFormValues> form={form} layout="vertical" requiredMark="optional">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="模型名称" name="name" rules={[{ required: true, message: '请输入模型名称' }]}>
                <Input placeholder="例如 GPT-4o" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="供应商" name="provider" rules={[{ required: true }]}>
                <Select options={providerOptions.map(value => ({ label: value, value }))} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="模型 ID" name="modelId" rules={[{ required: true, message: '请输入模型 ID' }]}>
                <Input placeholder="例如 gpt-4o" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="模型类型" name="type" rules={[{ required: true }]}>
                <Select options={typeOptions.map(value => ({ label: value, value }))} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="排序号" name="order" rules={[{ required: true }]}>
                <InputNumber min={1} max={models.length + 1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="状态" name="enabled" valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Drawer
        open={Boolean(usageModel)}
        title={`${usageModel?.name ?? ''} 用量详情`}
        size={680}
        onClose={() => setUsageModel(undefined)}
      >
        <Space vertical size={16} style={{ width: '100%' }}>
          <Typography.Title level={5} style={{ margin: 0 }}>
            用量概览
          </Typography.Title>
          <Row gutter={12}>
            <Col span={8}>
              <ProCard size="small" variant="outlined">
                <Statistic title="今日 Token" value={usageModel?.todayToken ?? 0} />
              </ProCard>
            </Col>
            <Col span={8}>
              <ProCard size="small" variant="outlined">
                <Statistic title="本月 Token" value={34567890} />
              </ProCard>
            </Col>
            <Col span={8}>
              <ProCard size="small" variant="outlined">
                <Statistic title="调用次数" value={12345} />
              </ProCard>
            </Col>
          </Row>
          <ProCard title="近 7 日用量趋势" size="small" variant="outlined">
            <Line {...usageLineConfig} />
          </ProCard>
          <ProCard title="最近调用" size="small" variant="outlined">
            <Table<RecentCall>
              rowKey="id"
              size="small"
              columns={recentColumns}
              dataSource={recentCalls}
              pagination={false}
            />
          </ProCard>
          <Button block type="primary" ghost>
            查看全部明细
          </Button>
        </Space>
      </Drawer>
    </>
  );
}
