// components/EnhancedProTable/EnhancedProTable.tsx

import {
  type ActionType,
  type ParamsType,
  ProTable,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { forwardRef, useCallback } from 'react';
import { formatPaginationTotal } from '@/utils/antd/tableHelpers';
import type { BaseRecord, EnhancedProTableProps } from './types';

function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
  props: EnhancedProTableProps<T, U>,
  ref: React.Ref<ActionType | undefined> | undefined,
) {
  const {
    columns,
    request,
    components,
    search = {},
    toolbarActions,
    rowKey = 'id',
    pagination = true,
    ...restProps
  } = props;

  const toolBarRender = useCallback(() => {
    const toolbarElements =
      toolbarActions?.map((action) => {
        return (
          <Button
            key={action.key}
            type={action.type}
            danger={action.danger}
            disabled={action.disabled}
            // icon={action.icon ?? <PlusOutlined />}
            onClick={() => action.onClick()}
          >
            {action.label}
          </Button>
        );
      }) || [];
    return toolbarElements;
  }, [toolbarActions]);
  return (
    <ProTable<T, U>
      {...restProps}
      columns={columns}
      actionRef={ref}
      request={request}
      rowKey={rowKey}
      rowSelection={props.rowSelection ?? false}
      toolBarRender={toolBarRender}
      manualRequest={false}
      showSorterTooltip
      // scroll={{ x: "max-content" }}
      scroll={{ x: 1200 }}
      components={components}
      search={
        search
          ? {
              labelWidth: 'auto',
              defaultCollapsed: false,
              ...search,
            }
          : false
      }
      options={
        search
          ? {
              fullScreen: true,
              reload: true,
              setting: true,
              density: true,
              ...restProps.options,
            }
          : false
      }
      pagination={
        pagination
          ? {
              showSizeChanger: true,
              showQuickJumper: true,
              pageSize: 10,
              showTotal: formatPaginationTotal,
            }
          : false
      }
    />
  );
}

export default forwardRef(EnhancedProTable) as <
  T extends BaseRecord,
  U extends ParamsType = any,
>(
  props: EnhancedProTableProps<T, U> & { ref?: React.Ref<ActionType> },
) => React.ReactElement;
