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

import { DeleteOutlined, EditOutlined, InboxOutlined, LoginOutlined, RedoOutlined } from "@ant-design/icons";
import { Button, Popconfirm, Space, Table, Tag, theme } from "antd";
import { useMemo } from "react";
import { useNavigate } from "react-router";

import type { Project, ProjectListResponse } from "../../../../shared/api";

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

interface ProjectTableProps {
  data: ProjectListResponse | undefined;
  loading: boolean;
  onArchive: (id: string) => Promise<void>;
  onChange: (
    pagination: { current?: number; pageSize?: number },
    sorter: { columnKey?: string; field?: string | string[]; order?: string },
  ) => void;
  onDelete: (id: string) => Promise<void>;
  onEdit: (project: Project) => void;
  onRestore: (id: string) => Promise<void>;
  page: number;
  pageSize: number;
  sortBy?: string;
  sortOrder?: string;
}

export function ProjectTable({
  data,
  loading,
  onArchive,
  onChange,
  onDelete,
  onEdit,
  onRestore,
  page,
  pageSize,
  sortBy,
  sortOrder,
}: ProjectTableProps) {
  const navigate = useNavigate();
  const { token: themeToken } = theme.useToken();

  const columns = useMemo<TableColumnsType<Project>>(
    () => [
      {
        dataIndex: "name",
        ellipsis: true,
        sorter: true,
        sortOrder:
          sortBy === "name" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
        title: "名称",
        width: 140,
      },
      { dataIndex: "description", ellipsis: true, title: "描述" },
      {
        align: "center",
        dataIndex: "status",
        render: (_value: unknown, record: Project) => {
          if (record.status === "archived") {
            return <Tag>已归档</Tag>;
          }
          return <Tag color={themeToken.colorPrimary}>进行中</Tag>;
        },
        title: "状态",
        width: 90,
      },
      {
        align: "center",
        dataIndex: "createdAt",
        render: (_value: unknown, record: Project) => formatDatetime(record.createdAt),
        sorter: true,
        sortOrder:
          sortBy === "createdAt" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
        title: "创建时间",
        width: 180,
      },
      {
        align: "center",
        dataIndex: "updatedAt",
        render: (_value: unknown, record: Project) => formatDatetime(record.updatedAt),
        sorter: true,
        sortOrder:
          sortBy === "updatedAt" ? (sortOrder === "asc" ? "ascend" : sortOrder === "desc" ? "descend" : null) : null,
        title: "更新时间",
        width: 180,
      },
      {
        dataIndex: "op",
        render: (_value: unknown, record: Project) => {
          if (record.status === "active") {
            return (
              <Space size="small">
                <Button
                  icon={<LoginOutlined />}
                  onClick={() => void navigate(`/workbench/${record.id}`)}
                  size="small"
                  type="link"
                >
                  工作台
                </Button>
                <Button icon={<EditOutlined />} onClick={() => onEdit(record)} size="small" type="link">
                  编辑
                </Button>
                <Popconfirm
                  description="归档后项目将变为只读。"
                  onConfirm={() => void onArchive(record.id)}
                  title="确认归档此项目？"
                >
                  <Button color="orange" icon={<InboxOutlined />} size="small" variant="link">
                    归档
                  </Button>
                </Popconfirm>
              </Space>
            );
          }
          return (
            <Space size="small">
              <Popconfirm onConfirm={() => void onRestore(record.id)} title="确认恢复此项目？">
                <Button icon={<RedoOutlined />} size="small" type="link">
                  恢复
                </Button>
              </Popconfirm>
              <Popconfirm
                description="此操作不可恢复。"
                onConfirm={() => void onDelete(record.id)}
                title="确认永久删除此项目？"
              >
                <Button danger icon={<DeleteOutlined />} size="small" type="link">
                  删除
                </Button>
              </Popconfirm>
            </Space>
          );
        },
        title: "操作",
        width: 260,
      },
    ],
    [navigate, onEdit, onArchive, onRestore, onDelete, sortBy, sortOrder, themeToken.colorPrimary],
  );

  const handleTableChange: TableProps<Project>["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"
    />
  );
}
