import { Button, Table, Tag, Popconfirm, Space, Card } from 'tdesign-react'
import type { Provider, Model } from '@/types'
import { ModelTable } from './ModelTable'
import type { PrimaryTableCol } from 'tdesign-react/es/table/type'

interface ProviderTableProps {
  providers: Provider[]
  loading: boolean
  onAdd: () => void
  onEdit: (provider: Provider) => void
  onDelete: (id: string) => void
  onAddModel: (providerId: string) => void
  onEditModel: (model: Model) => void
}

export function ProviderTable({
  providers,
  loading,
  onAdd,
  onEdit,
  onDelete,
  onAddModel,
  onEditModel,
}: ProviderTableProps) {
  const columns: PrimaryTableCol<Provider>[] = [
    {
      title: '名称',
      colKey: 'name',
      width: 180,
      ellipsis: true,
    },
    {
      title: 'Base URL',
      colKey: 'baseUrl',
      ellipsis: true,
    },
    {
      title: '协议',
      colKey: 'protocol',
      width: 100,
      cell: ({ row }) => (
        <Tag theme={row.protocol === 'openai' ? 'primary' : 'success'} variant='light' shape='round'>
          {row.protocol === 'openai' ? 'OpenAI' : 'Anthropic'}
        </Tag>
      ),
    },
    {
      title: 'API Key',
      colKey: 'apiKey',
      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: 160,
      cell: ({ row }) => (
        <Space>
          <Button variant='text' size='small' onClick={() => onEdit(row)}>
            编辑
          </Button>
          <Popconfirm content='确定要删除这个供应商吗？关联的模型也会被删除。' onConfirm={() => onDelete(row.id)}>
            <Button variant='text' theme='danger' size='small'>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <Card
      title='供应商列表'
      headerBordered
      hoverShadow
      actions={
        <Button theme='primary' onClick={onAdd}>
          添加供应商
        </Button>
      }
    >
      <Table<Provider>
        columns={columns}
        data={providers}
        rowKey='id'
        loading={loading}
        stripe
        expandedRow={({ row }) => (
          <ModelTable providerId={row.id} onAdd={() => onAddModel(row.id)} onEdit={onEditModel} />
        )}
        pagination={undefined}
        empty='暂无供应商，点击上方按钮添加'
      />
    </Card>
  )
}
