import React from "react";
import { Table } from "antd";
import type { TablePaginationConfig, TableProps } from "antd";
import "./ListTable.css";
import i18n from "../../../i18n";

export type ListTableProps<T extends Record<string, any>> = {
  columns: TableProps<T>["columns"];
  dataSource: T[];
  rowKey?: string;
  selectedRowKeys?: React.Key[];
  onSelectionChange?: (keys: React.Key[]) => void;
  isAllPagesSelected?: boolean;
  totalCount?: number;
  onSelectAllPages?: () => void;
  onClearSelection?: () => void;
  pagination?: TablePaginationConfig | false;
  scroll?: { x?: number | true | string; y?: number | string };
  onRowClick?: (record: T) => void;
  selectedRow?: T | null;
  loading?: boolean;
  className?: string;
  onChange?: TableProps<T>["onChange"];
};

function ListTable<T extends Record<string, any>>({
  columns,
  dataSource,
  rowKey = "id",
  selectedRowKeys = [],
  onSelectionChange,
  isAllPagesSelected = false,
  totalCount,
  onSelectAllPages,
  onClearSelection,
  pagination = {
    pageSize: 10,
    showSizeChanger: { showSearch: false },
    showQuickJumper: true,
  },
  scroll = { x: 1200 },
  onRowClick,
  selectedRow,
  loading = false,
  className = "",
  onChange,
}: ListTableProps<T>) {
  const mergedScroll = React.useMemo(() => {
    return {
      x: 1200,
      ...scroll,
    };
  }, [scroll]);

  const hasVerticalScroll = mergedScroll.y !== undefined;
  const rowSelection: TableProps<T>["rowSelection"] = onSelectionChange
    ? {
        selectedRowKeys,
        onChange: (newSelectedRowKeys: React.Key[]) => {
          onSelectionChange?.(newSelectedRowKeys);
        },
        getCheckboxProps: () => ({
          disabled: isAllPagesSelected,
        }),
      }
    : undefined;

  const mergedPagination =
    pagination === false
      ? false
      : (() => {
          const mergedShowSizeChanger =
            pagination.showSizeChanger === undefined || pagination.showSizeChanger === true
              ? { showSearch: false }
              : pagination.showSizeChanger;

          return {
          ...pagination,
          className: ["app-global-pagination", pagination.className].filter(Boolean).join(" "),
          showSizeChanger: mergedShowSizeChanger,
          showTotal: (total: number) => (
            <div className="table-selection-info">
              {isAllPagesSelected ? (
                <>
                  <span className="selection-count">
                    已选择 <span className="count-highlight">{totalCount || total}</span> 项
                  </span>
                  {onClearSelection && (
                    <a onClick={onClearSelection} className="selection-action">
                      清除选择
                    </a>
                  )}
                </>
              ) : selectedRowKeys.length > 0 ? (
                <>
                  <span className="selection-count">
                    已选择 <span className="count-highlight">{selectedRowKeys.length}</span> 项
                  </span>
                  {onSelectAllPages && selectedRowKeys.length < (totalCount || total) && (
                    <a onClick={onSelectAllPages} className="selection-action">
                      选择全部 {totalCount || total} 项
                    </a>
                  )}
                  {onClearSelection && (
                    <a onClick={onClearSelection} className="selection-action">
                      清除
                    </a>
                  )}
                </>
              ) : (
                <span className="selection-count">
                  {i18n.t("common.total", { total: totalCount || total })}
                </span>
              )}
            </div>
          ),
        };
      })();

  const wrapperStyle = hasVerticalScroll
    ? ({
      ["--list-table-scroll-y" as string]: typeof mergedScroll.y === "number" ? `${mergedScroll.y}px` : mergedScroll.y,
    } as React.CSSProperties)
    : undefined;

  return (
    <div className={`list-table-container ${className}`} style={wrapperStyle}>
      <Table
        className={hasVerticalScroll ? "list-table-table--y-scroll" : undefined}
        size="middle"
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        rowKey={rowKey}
        pagination={mergedPagination}
        scroll={mergedScroll}
        loading={loading}
        onChange={onChange}
        onRow={(record) => ({
          onClick: () => onRowClick?.(record),
          className: selectedRow?.[rowKey] === record[rowKey] ? "row-selected" : "",
        })}
      />
    </div>
  );
}

export default ListTable;
