import { Button, Table, Tag, Popconfirm, Space } from 'tdesign-react'
import { useModels, useDeleteModel } from '@/hooks/useModels'
import type { Model } from '@/types'
import type { PrimaryTableCol } from 'tdesign-react/es/table/type'

interface ModelTableProps {
  providerId: string
  onAdd?: () => void
  onEdit?: (model: Model) => void
}

export function ModelTable({ providerId, onAdd, onEdit }: ModelTableProps) {
  const { data: models = [], isLoading } = useModels(providerId)
  const deleteModel = useDeleteModel()

  const columns: PrimaryTableCol<Model>[] = [
    {
      title: '统一模型 ID',
      colKey: 'unifiedId',
      width: 250,
      ellipsis: true,
      cell: ({ row }) => row.unifiedId || `${row.providerId}/${row.modelName}`,
    },
    {
      title: '模型名称',
      colKey: 'modelName',
      ellipsis: true,
    },
    {
      title: '状态',
      colKey: 'enabled',
      width: 80,
      cell: ({ row }) =>
        row.enabled ? (
          <Tag theme='success' variant='light' shape='round'>
            启用
          </Tag>
        ) : (
          <Tag theme='danger' variant='light' shape='round'>
            禁用
          </Tag>
        ),
    },
    {
      title: '操作',
      colKey: 'action',
      width: 120,
      cell: ({ row }) => (
        <Space>
          {onEdit && (
            <Button variant='text' size='small' onClick={() => onEdit(row)}>
              编辑
            </Button>
          )}
          <Popconfirm content='确定要删除这个模型吗？' onConfirm={() => deleteModel.mutate(row.id)}>
            <Button variant='text' theme='danger' size='small'>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div style={{ padding: '8px 16px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{ fontWeight: 500 }}>关联模型 ({models.length})</span>
        {onAdd && (
          <Button variant='text' size='small' onClick={onAdd}>
            添加模型
          </Button>
        )}
      </div>
      <Table<Model>
        columns={columns}
        data={models}
        rowKey='id'
        loading={isLoading}
        stripe
        pagination={undefined}
        size='small'
        empty='暂无模型，点击上方按钮添加'
      />
    </div>
  )
}
