import type { TableColumnsType, TableProps } from "antd";

import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import { Button, Popconfirm, Space, Table } from "antd";
import { useMemo } from "react";

import type { Provider, ProviderListResponse } from "../../../../shared/api";

import { formatDatetime } from "../../../shared/utils/format";

interface ProviderTableProps {
  data: ProviderListResponse | undefined;
  loading: boolean;
  onChange: (
    pagination: { current?: number; pageSize?: number },
    sorter: { columnKey?: string; field?: string | string[]; order?: string },
  ) => void;
  onDelete: (id: string) => Promise<void>;
  onEdit: (provider: Provider) => void;
  page: number;
  pageSize: number;
  sortBy?: string;
  sortOrder?: string;
}

export function ProviderTable({
  data,
  loading,
  onChange,
  onDelete,
  onEdit,
  page,
  pageSize,
  sortBy,
  sortOrder,
}: ProviderTableProps) {
  const columns = useMemo<TableColumnsType<Provider>>(
    () => [
      {
        dataIndex: "name",
        ellipsis: true,
        sorter: true,
        sortOrder:
          sortBy === "name" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
        title: "名称",
        width: 180,
      },
      {
        dataIndex: "type",
        render: (_value: unknown, record: Provider) => {
          const labels: Record<string, string> = {
            anthropic: "Anthropic",
            openai: "OpenAI",
            "openai-compatible": "OpenAI 兼容",
          };
          return labels[record.type] ?? record.type;
        },
        title: "类型",
        width: 140,
      },
      { dataIndex: "baseUrl", ellipsis: true, title: "Base URL" },
      {
        align: "center",
        dataIndex: "createdAt",
        render: (_value: unknown, record: Provider) => formatDatetime(record.createdAt),
        sorter: true,
        sortOrder:
          sortBy === "createdAt" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
        title: "创建时间",
        width: 180,
      },
      {
        dataIndex: "op",
        render: (_value: unknown, record: Provider) => (
          <Space size="small">
            <Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
              编辑
            </Button>
            <Popconfirm
              description="删除后关联的模型将无法使用。"
              onConfirm={() => void onDelete(record.id)}
              title="确认删除此供应商？"
            >
              <Button danger icon={<DeleteOutlined />} size="small" type="link">
                删除
              </Button>
            </Popconfirm>
          </Space>
        ),
        title: "操作",
        width: 180,
      },
    ],
    [onEdit, onDelete, sortBy, sortOrder],
  );

  const handleTableChange: TableProps<Provider>["onChange"] = (pagination, _filters, sorter) => {
    const sortInfo =
      sorter && typeof sorter === "object" && "columnKey" in sorter
        ? (sorter as { columnKey?: string; field?: string | string[]; order?: string })
        : {};
    onChange({ current: pagination.current, pageSize: pagination.pageSize }, sortInfo);
  };

  return (
    <Table
      columns={columns}
      dataSource={data?.items ?? []}
      loading={loading}
      locale={{ emptyText: "暂无供应商数据" }}
      onChange={handleTableChange}
      pagination={{
        current: page,
        hideOnSinglePage: false,
        pageSize,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条`,
        total: data?.total ?? 0,
      }}
      rowKey="id"
    />
  );
}
