import { Button, Table, Tag, Popconfirm, Space, Card, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { Provider, Model } from '@/types';
import { ModelTable } from './ModelTable';

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

function maskApiKey(key: string | null | undefined): string {
  if (!key) return '****';
  if (key.length <= 4) return '****';
  return `****${key.slice(-4)}`;
}

export function ProviderTable({
  providers,
  loading,
  onAdd,
  onEdit,
  onDelete,
  onAddModel,
  onEditModel,
}: ProviderTableProps) {
  const columns: ColumnsType<Provider> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      ellipsis: { showTitle: true },
    },
    {
      title: 'Base URL',
      dataIndex: 'baseUrl',
      key: 'baseUrl',
      ellipsis: { showTitle: true },
    },
    {
      title: 'API Key',
      dataIndex: 'apiKey',
      key: 'apiKey',
      width: 120,
      ellipsis: { showTitle: true },
      render: (key: string | null | undefined) => (
        <Tooltip title={maskApiKey(key)}>
          <span>{maskApiKey(key)}</span>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled: boolean) =>
        enabled ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>,
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button variant="link" size="small" onClick={() => onEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个供应商吗？关联的模型也会被删除。"
            onConfirm={() => onDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button variant="link" color="danger" size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="供应商列表"
      extra={
        <Button color="primary" variant="solid" onClick={onAdd}>
          添加供应商
        </Button>
      }
    >
      <Table<Provider>
        columns={columns}
        dataSource={providers}
        rowKey="id"
        loading={loading}
        expandable={{
          expandedRowRender: (record) => (
            <ModelTable
              providerId={record.id}
              onAdd={() => onAddModel(record.id)}
              onEdit={onEditModel}
            />
          ),
        }}
        pagination={false}
        scroll={{ x: 840 }}
        locale={{ emptyText: '暂无供应商，点击上方按钮添加' }}
      />
    </Card>
  );
}
