import { KhovtTransPhieuXuatWithRelations } from 'main/apis/drc/models';
import { BasicSpinner } from 'main/components/atoms/spiner';
import { Page } from 'main/constants';
import { useState } from 'react';
import BootstrapTable, { TableChangeState, TableChangeType } from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';
import ToolkitProvider, { CSVExport } from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit';
import { useNavigate } from 'react-router-dom';
import { Button } from 'reactstrap';
import tableConfig from './table-config';

const { ExportCSVButton } = CSVExport;

export type ExportTable = {
  page: number;
  sizePerPage: number;
  sortField?: string;
  sortOrder?: string;
};

enum FieldName {
  ID = 'id',
  PAGE = 'page',
  SIZE_PER_PAGE = 'sizePerPage',
  SORT_BY = 'sortBy',
  SORT_TYPE = 'sortType',
}

type Props = {
  data?: KhovtTransPhieuXuatWithRelations[];
  dataIsLoading: boolean;
  dataCount?: number;
  dataCountIsLoading: boolean;
  tableState: ExportTable;
  handleTableStateChange: (type: TableChangeType, newState: TableChangeState<KhovtTransPhieuXuatWithRelations>) => void;
};

const getSyncSelectedRows = (selectedRows: number[], data: KhovtTransPhieuXuatWithRelations[]) => {
  const newSelectedRows = [...selectedRows];
  for (const selectedRow of selectedRows) {
    const rowDataIndex = data.findIndex((item) => item.id === selectedRow);
    if (rowDataIndex === -1) {
      const removedIndex = newSelectedRows.indexOf(selectedRow);
      newSelectedRows.splice(removedIndex, 1);
    }
  }
  return newSelectedRows;
};

function SuppliesStoreExportTable({
  data,
  dataIsLoading,
  dataCount,
  dataCountIsLoading,
  tableState: { page, sizePerPage, sortField, sortOrder },
  handleTableStateChange,
}: Props) {
  // React Router
  const navigate = useNavigate();

  // React State
  const [selectedRows, setSelectedRows] = useState<number[]>([]);

  // React Function
  const handleOnSelect = (row: KhovtTransPhieuXuatWithRelations, isSelect: boolean) => {
    if (!row || !row.id || !data) {
      return;
    }

    // Sync selected rows with data table
    const newSelectedRows = getSyncSelectedRows(selectedRows, data);

    if (isSelect) {
      setSelectedRows([...newSelectedRows, row.id]);
    } else {
      setSelectedRows(newSelectedRows.filter((id) => id !== row.id));
    }
  };

  const handleOnSelectAll = (isSelect: boolean, rows: KhovtTransPhieuXuatWithRelations[]) => {
    const ids = rows.map((row) => row.id);

    if (isSelect) {
      setSelectedRows(ids as number[]);
    } else {
      setSelectedRows([]);
    }
  };

  const handleTableChangeWrapper = (
    type: TableChangeType,
    newState: TableChangeState<KhovtTransPhieuXuatWithRelations>,
  ) => {
    if (data) {
      setSelectedRows(getSyncSelectedRows(selectedRows, data));
    }

    handleTableStateChange(type, newState);
  };

  return (
    <ToolkitProvider
      data={data || []}
      keyField={FieldName.ID}
      columns={tableConfig.columns}
      exportCSV={tableConfig.exportCSV}>
      {(props: any) => (
        <>
          <div className="d-flex justify-content-end mb-4 pb-1">
            <Button className="btn-neutral" onClick={() => navigate(Page.SUPPLIES_STORE_EXPORT_ADD.PATH)}>
              Thêm mới
            </Button>
            <ExportCSVButton className="btn-neutral" {...props.csvProps}>
              Tải phiếu xuất
            </ExportCSVButton>
          </div>
          <div className="table-responsive">
            <BootstrapTable
              {...props.baseProps}
              remote
              bootstrap4
              bordered={false}
              pagination={paginationFactory({
                ...tableConfig.pagination,
                page: page,
                sizePerPage: sizePerPage,
                totalSize: dataCount,
              })}
              sort={
                sortField
                  ? {
                      dataField: sortField,
                      order: sortOrder,
                    }
                  : {}
              }
              selectRow={{
                ...tableConfig.selectRow,
                selected: selectedRows,
                onSelect: handleOnSelect,
                onSelectAll: handleOnSelectAll,
              }}
              onTableChange={handleTableChangeWrapper}
              noDataIndication={() => (
                <div className="text-center">
                  {dataIsLoading || dataCountIsLoading ? <BasicSpinner /> : 'Không có kết quả nào được tìm thấy'}
                </div>
              )}
            />
          </div>
        </>
      )}
    </ToolkitProvider>
  );
}

export default SuppliesStoreExportTable;
