import { useState } from 'react'
import {
  Button, Divider, Empty, Form, Input, InputNumber, message, Popconfirm, Select, Space, Switch, Table, Tag,
  Tooltip,
} from 'antd'
import {
  ApiOutlined, DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined,
} from '@ant-design/icons'
import {
  modelConfigsApi, type ModelCapability, type ModelConfig, type ModelConfigPayload, type ModelModality,
  type ModelProtocol,
} from '../api'
import FormDrawer from '../components/FormDrawer'
import PageWrapper from '../components/PageWrapper'
import { useResource } from '../hooks/useResource'
import { formatDateTime } from '../utils/date'
import { notifyModelConfigsChanged } from '../utils/modelConfigEvents'

const capabilityLabels: Record<ModelCapability, string> = {
  chat: '对话',
  embedding: '向量',
  moderation: '内容审核',
}

const capabilityColors: Record<ModelCapability, string> = {
  chat: 'blue',
  embedding: 'green',
  moderation: 'orange',
}

const modalityLabels: Record<ModelModality, string> = {
  text: '文本',
  image: '图像',
  audio: '音频',
  video: '视频',
}

const modalityOptions = Object.entries(modalityLabels).map(([value, label]) => ({ value, label }))

const featureLabels: Array<[keyof Pick<
  ModelConfig,
  'supports_streaming' | 'supports_tool_calling' | 'supports_structured_output' | 'supports_reasoning'
>, string]> = [
  ['supports_streaming', '流式'],
  ['supports_tool_calling', '工具调用'],
  ['supports_structured_output', '结构化输出'],
  ['supports_reasoning', '推理'],
]

const formatTokens = (value: number | null) => value ? new Intl.NumberFormat('zh-CN').format(value) : '-'

const compactTokens = (value: number | null) => {
  if (!value) return '-'
  if (value >= 1000000 && value % 100000 === 0) return `${value / 1000000}M`
  if (value >= 1000) return `${Math.round(value / 1000)}K`
  return String(value)
}

const protocolOptions: Record<ModelProtocol, {
  label: string
  capabilities: ModelCapability[]
  endpointPlaceholder: string
}> = {
  openai_compatible: {
    label: 'OpenAI 兼容',
    capabilities: ['chat', 'embedding', 'moderation'],
    endpointPlaceholder: 'https://api.example.com/v1/chat/completions',
  },
  anthropic: {
    label: 'Anthropic Messages',
    capabilities: ['chat'],
    endpointPlaceholder: 'https://api.anthropic.com/v1/messages',
  },
  google_gemini: {
    label: 'Google Gemini',
    capabilities: ['chat'],
    endpointPlaceholder: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent',
  },
  dashscope: {
    label: 'DashScope 原生',
    capabilities: ['chat'],
    endpointPlaceholder: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
  },
}

export default function ModelConfigsPage() {
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [editing, setEditing] = useState<ModelConfig | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [testingId, setTestingId] = useState<string | null>(null)
  const [capability, setCapability] = useState<ModelCapability | undefined>()
  const [enabled, setEnabled] = useState<boolean | undefined>()
  const [form] = Form.useForm<ModelConfigPayload>()
  const selectedProtocol = Form.useWatch('provider', form) || 'openai_compatible'
  const selectedProtocolMeta = protocolOptions[selectedProtocol]

  const { data: configs, loading, reload } = useResource(
    () => modelConfigsApi.list({ capability, enabled }).then((r) => r.data),
    { tabPath: '/models', deps: [capability, enabled] },
  )

  const openCreate = () => {
    setEditing(null)
    form.resetFields()
    form.setFieldsValue({
      provider: 'openai_compatible',
      capability: 'chat',
      vendor_name: '',
      input_modalities: ['text'],
      output_modalities: ['text'],
      context_window: null,
      max_output_tokens: null,
      supports_streaming: false,
      supports_tool_calling: false,
      supports_structured_output: false,
      supports_reasoning: false,
      region: '',
      documentation_url: null,
      enabled: true,
      is_default: false,
      is_analysis_default: false,
      description: '',
    })
    setDrawerOpen(true)
  }

  const openEdit = (config: ModelConfig) => {
    setEditing(config)
    form.setFieldsValue({
      name: config.name,
      provider: config.provider,
      capability: config.capability,
      endpoint_url: config.endpoint_url,
      model_name: config.model_name,
      vendor_name: config.vendor_name,
      input_modalities: config.input_modalities,
      output_modalities: config.output_modalities,
      context_window: config.context_window,
      max_output_tokens: config.max_output_tokens,
      supports_streaming: config.supports_streaming,
      supports_tool_calling: config.supports_tool_calling,
      supports_structured_output: config.supports_structured_output,
      supports_reasoning: config.supports_reasoning,
      region: config.region,
      documentation_url: config.documentation_url,
      api_key: null,
      clear_api_key: false,
      enabled: config.enabled,
      is_default: config.is_default,
      is_analysis_default: config.is_analysis_default,
      description: config.description,
    })
    setDrawerOpen(true)
  }

  const changeProtocol = (provider: ModelProtocol) => {
    const supportedCapabilities = protocolOptions[provider].capabilities
    if (!supportedCapabilities.includes(form.getFieldValue('capability'))) {
      form.setFieldValue('capability', supportedCapabilities[0])
    }
  }

  const submit = async () => {
    const values = await form.validateFields()
    const payload: ModelConfigPayload = {
      ...values,
      api_key: values.api_key || null,
      model_name: values.model_name || null,
      vendor_name: values.vendor_name || '',
      region: values.region || '',
      documentation_url: values.documentation_url || null,
      description: values.description || '',
    }
    if (editing) {
      setSubmitting(true)
      try {
        await modelConfigsApi.update(editing.id, payload)
        message.success('模型配置已更新')
      } finally {
        setSubmitting(false)
      }
    } else {
      setSubmitting(true)
      try {
        await modelConfigsApi.create(payload)
        message.success('模型配置已创建')
      } finally {
        setSubmitting(false)
      }
    }
    notifyModelConfigsChanged()
    setDrawerOpen(false)
    reload()
  }

  const testConnection = async (config: ModelConfig) => {
    setTestingId(config.id)
    try {
      const response = await modelConfigsApi.test(config.id)
      if (response.data.ok) message.success(`${config.name} 连接成功`)
      else message.warning(response.data.message)
    } finally {
      setTestingId(null)
    }
  }

  const remove = async (config: ModelConfig) => {
    await modelConfigsApi.delete(config.id)
    message.success('模型配置已删除')
    notifyModelConfigsChanged()
    reload()
  }

  const columns = [
    {
      // 配置名称 + 默认/厂商/区域 + Endpoint 摘要
      title: '配置名称', dataIndex: 'name', key: 'name',
      render: (value: string, record: ModelConfig) => (
        <div style={{ minWidth: 0 }}>
          <Space size={6}>
            <Tooltip title={record.description || undefined}>
              <span style={{ fontWeight: 500 }}>{value}</span>
            </Tooltip>
            {record.is_default && <Tag color="gold" style={{ margin: 0 }}>默认</Tag>}
            {record.is_analysis_default && <Tag color="purple" style={{ margin: 0 }}>分析默认</Tag>}
          </Space>
          <Tooltip title={record.endpoint_url}>
            <div style={{
              color: '#8c8c8c', fontSize: 12, marginTop: 3,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 260,
            }}>
              {[record.vendor_name, record.region].filter(Boolean).join(' · ') || record.endpoint_url}
            </div>
          </Tooltip>
        </div>
      ),
    },
    {
      // 模型名 + 协议
      title: '模型 / 协议', key: 'model', width: 200,
      render: (_: unknown, record: ModelConfig) => (
        <div style={{ minWidth: 0 }}>
          <div style={{
            fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 180,
          }}>
            {record.model_name || '-'}
          </div>
          <div style={{ color: '#8c8c8c', fontSize: 12, marginTop: 3 }}>
            {protocolOptions[record.provider]?.label || record.provider}
          </div>
        </div>
      ),
    },
    {
      // 能力 + 输入/输出模态
      title: '能力 / 模态', key: 'capability', width: 200,
      render: (_: unknown, record: ModelConfig) => {
        const modalityLine = (values: ModelModality[]) =>
          values.map((v) => modalityLabels[v]).join('、')
        return (
          <Space size={6} align="start">
            <Tag color={capabilityColors[record.capability]} style={{ margin: 0 }}>
              {capabilityLabels[record.capability]}
            </Tag>
            <span style={{ color: '#8c8c8c', fontSize: 12, lineHeight: '22px' }}>
              {modalityLine(record.input_modalities)} → {modalityLine(record.output_modalities)}
            </span>
          </Space>
        )
      },
    },
    {
      // 上下文/最大输出 + 特性
      title: '规格 / 特性', key: 'spec', width: 210,
      render: (_: unknown, record: ModelConfig) => {
        const enabledFeatures = featureLabels.filter(([key]) => record[key])
        return (
          <div style={{ fontSize: 12 }}>
            <Tooltip title={`上下文 ${formatTokens(record.context_window)} / 最大输出 ${formatTokens(record.max_output_tokens)}`}>
              <span>
                <span style={{ color: '#8c8c8c' }}>上下文 </span>{compactTokens(record.context_window)}
                <span style={{ color: '#8c8c8c' }}>　输出 </span>{compactTokens(record.max_output_tokens)}
              </span>
            </Tooltip>
            {enabledFeatures.length > 0 && (
              <div style={{ marginTop: 4, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                {enabledFeatures.map(([key, label]) => (
                  <Tag key={key} style={{ margin: 0, fontSize: 11, lineHeight: '18px', padding: '0 5px' }}>{label}</Tag>
                ))}
              </div>
            )}
          </div>
        )
      },
    },
    {
      // 状态 + 凭据 + 更新时间
      title: '状态', key: 'status', width: 150,
      render: (_: unknown, record: ModelConfig) => (
        <div>
          <Space size={4}>
            {record.enabled ? <Tag color="success" style={{ margin: 0 }}>启用</Tag> : <Tag style={{ margin: 0 }}>停用</Tag>}
            {record.has_api_key
              ? <Tag color="blue" style={{ margin: 0 }}>有凭据</Tag>
              : <Tag style={{ margin: 0 }}>无凭据</Tag>}
          </Space>
          <Tooltip title={`更新于 ${formatDateTime(record.updated_at)}`}>
            <div style={{ color: '#8c8c8c', fontSize: 12, marginTop: 3 }}>
              {formatDateTime(record.updated_at)}
            </div>
          </Tooltip>
        </div>
      ),
    },
    {
      title: '操作', key: 'actions', width: 110,
      render: (_: unknown, record: ModelConfig) => (
        <Space size={2}>
          <Tooltip title="连接测试">
            <Button
              type="text"
              size="small"
              icon={<ApiOutlined />}
              loading={testingId === record.id}
              disabled={!record.enabled}
              onClick={() => testConnection(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button type="text" size="small" icon={<EditOutlined />} onClick={() => openEdit(record)} />
          </Tooltip>
          <Popconfirm title="删除该模型配置？" onConfirm={() => remove(record)}>
            <Tooltip title="删除">
              <Button type="text" size="small" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <PageWrapper
      title="模型配置"
      description="统一管理评测工程使用的外部模型连接"
      inline
      fullHeight
      extra={
        <Space>
          <Select
            allowClear
            placeholder="全部能力"
            style={{ width: 120 }}
            value={capability}
            onChange={setCapability}
            options={Object.entries(capabilityLabels).map(([value, label]) => ({ value, label }))}
          />
          <Select
            allowClear
            placeholder="全部状态"
            style={{ width: 110 }}
            value={enabled}
            onChange={setEnabled}
            options={[{ value: true, label: '启用' }, { value: false, label: '停用' }]}
          />
          <Tooltip title="刷新"><Button icon={<ReloadOutlined />} onClick={() => reload()} /></Tooltip>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>新增</Button>
        </Space>
      }
    >
      <div style={{ height: '100%', overflowY: 'auto', padding: '0 16px 16px' }}>
        <Table
          dataSource={configs ?? []}
          columns={columns}
          rowKey="id"
          loading={loading}
          pagination={(configs?.length ?? 0) > 20 ? { pageSize: 20, showTotal: (t) => `共 ${t} 个` } : false}
          locale={{ emptyText: <Empty description="还没有模型配置" /> }}
          tableLayout="auto"
        />
      </div>

      <FormDrawer
        title={editing ? '编辑模型配置' : '新增模型配置'}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        onSubmit={submit}
        submitting={submitting}
        okText="保存"
      >
        <Form form={form} layout="vertical">
          <Divider orientation="left" plain style={{ marginTop: 0 }}>基础信息</Divider>
          <Form.Item name="name" label="配置名称" rules={[{ required: true, message: '请输入配置名称' }]}>
            <Input placeholder="例如：评估对话模型" />
          </Form.Item>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Form.Item name="vendor_name" label="厂商 / 平台">
              <Input placeholder="例如：阿里云百炼" />
            </Form.Item>
            <Form.Item name="region" label="部署区域">
              <Input placeholder="例如：华北 2（北京）" />
            </Form.Item>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Form.Item name="input_modalities" label="输入模态" rules={[{ required: true, message: '请选择输入模态' }]}>
              <Select mode="multiple" options={modalityOptions} />
            </Form.Item>
            <Form.Item name="output_modalities" label="输出模态" rules={[{ required: true, message: '请选择输出模态' }]}>
              <Select mode="multiple" options={modalityOptions} />
            </Form.Item>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Form.Item name="context_window" label="上下文窗口（Token）">
              <InputNumber min={1} precision={0} style={{ width: '100%' }} placeholder="例如：128000" />
            </Form.Item>
            <Form.Item name="max_output_tokens" label="最大输出（Token）">
              <InputNumber min={1} precision={0} style={{ width: '100%' }} placeholder="例如：8192" />
            </Form.Item>
          </div>
          <Form.Item name="documentation_url" label="官方文档地址" rules={[{ type: 'url', message: '请输入有效 URL' }]}>
            <Input placeholder="https://..." />
          </Form.Item>
          <Form.Item name="description" label="说明">
            <Input.TextArea rows={3} placeholder="该配置的使用范围或注意事项" />
          </Form.Item>

          <Divider orientation="left" plain>模型特性</Divider>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 20px' }}>
            <Form.Item name="supports_streaming" label="流式输出" valuePropName="checked"><Switch /></Form.Item>
            <Form.Item name="supports_tool_calling" label="工具调用" valuePropName="checked"><Switch /></Form.Item>
            <Form.Item name="supports_structured_output" label="结构化输出" valuePropName="checked"><Switch /></Form.Item>
            <Form.Item name="supports_reasoning" label="推理模型" valuePropName="checked"><Switch /></Form.Item>
          </div>

          <Divider orientation="left" plain>连接设置</Divider>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Form.Item name="provider" label="协议" rules={[{ required: true }]}>
              <Select
                onChange={changeProtocol}
                options={Object.entries(protocolOptions).map(([value, option]) => ({ value, label: option.label }))}
              />
            </Form.Item>
            <Form.Item name="capability" label="能力" rules={[{ required: true }]}>
              <Select
                onChange={(value) => {
                  if (value !== 'chat') form.setFieldValue('is_analysis_default', false)
                }}
                options={selectedProtocolMeta.capabilities.map((value) => ({ value, label: capabilityLabels[value] }))}
              />
            </Form.Item>
          </div>
          <Form.Item name="endpoint_url" label="完整 Endpoint URL" rules={[{ required: true, message: '请输入 Endpoint URL' }, { type: 'url', message: '请输入有效 URL' }]}>
            <Input placeholder={selectedProtocolMeta.endpointPlaceholder} />
          </Form.Item>
          <Form.Item shouldUpdate noStyle>
            {() => form.getFieldValue('capability') !== 'moderation' && (
              <Form.Item name="model_name" label="模型名称" rules={[{ required: true, message: '请输入模型名称' }]}>
                <Input placeholder="例如：gpt-4o-mini" />
              </Form.Item>
            )}
          </Form.Item>
          <Form.Item name="api_key" label="API Key" extra={editing?.has_api_key ? '已配置；留空将保留现有凭据' : undefined}>
            <Input.Password autoComplete="new-password" placeholder={editing?.has_api_key ? '留空保留现有凭据' : '可选'} />
          </Form.Item>
          {editing?.has_api_key && (
            <Form.Item name="clear_api_key" label="清除现有凭据" valuePropName="checked">
              <Switch />
            </Form.Item>
          )}
          <Space size={24}>
            <Form.Item name="enabled" label="启用" valuePropName="checked"><Switch /></Form.Item>
            <Form.Item name="is_default" label="设为该能力默认配置" valuePropName="checked"><Switch /></Form.Item>
            <Form.Item shouldUpdate noStyle>
              {() => form.getFieldValue('capability') === 'chat' && (
                <Form.Item
                  name="is_analysis_default"
                  label="设为分析默认"
                  tooltip="活动智能分析使用的全局默认模型，全局唯一"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
              )}
            </Form.Item>
          </Space>
        </Form>
      </FormDrawer>
    </PageWrapper>
  )
}
