import { KhovtMasterVtWithRelations } from 'main/apis/drc/models';
import { BasicSpinner } from 'main/components/atoms/spiner';
import { useMemo } from 'react';
import BootstrapTable, { TableChangeState, TableChangeType } from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';
import paginationFactory from 'react-bootstrap-table2-paginator';
import ToolkitProvider from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit';
import tableConfig from './table-config';

export type ExportTable = {
  page: number;
  sizePerPage: number;
  sortField?: string;
  sortOrder?: string;
  selectedRows?: KhovtMasterVtWithRelations[];
};

enum FieldName {
  SUPPLIES_CODE = 'maVt',
  PAGE = 'page',
  SIZE_PER_PAGE = 'sizePerPage',
  SORT_BY = 'sortBy',
  SORT_TYPE = 'sortType',
}

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

const getSyncSelectedRows = (data: KhovtMasterVtWithRelations[], selectedRows?: KhovtMasterVtWithRelations[]) => {
  if (!selectedRows) {
    return [];
  }
  const newSelectedRows = [...selectedRows];
  for (const selectedRow of selectedRows) {
    const rowDataIndex = data.findIndex((item) => item.maVt === selectedRow.maVt);
    if (rowDataIndex === -1) {
      const removedIndex = newSelectedRows.findIndex((item) => selectedRow.maVt === item.maVt);
      newSelectedRows.splice(removedIndex, 1);
    }
  }
  return newSelectedRows;
};

function AddSuppliesModalTable({
  data,
  dataIsLoading,
  dataCount,
  dataCountIsLoading,
  tableState: { page, sizePerPage, sortField, sortOrder, selectedRows },
  handleTableStateChange,
  handleSelectedRowsChange,
}: Props) {
  // React State
  const selectedRowIds = useMemo(() => {
    return selectedRows?.map((row) => row.maVt);
  }, [selectedRows]);

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

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

    if (isSelect) {
      handleSelectedRowsChange([...newSelectedRows, row]);
    } else {
      handleSelectedRowsChange(newSelectedRows.filter((item) => item.maVt !== row.maVt));
    }
  };

  const handleOnSelectAll = (isSelect: boolean, rows: KhovtMasterVtWithRelations[]) => {
    if (isSelect) {
      handleSelectedRowsChange(rows);
    } else {
      handleSelectedRowsChange([]);
    }
  };

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

    handleTableStateChange(type, newState);
  };

  return (
    <ToolkitProvider data={data || []} keyField={FieldName.SUPPLIES_CODE} columns={tableConfig.columns}>
      {(props: any) => (
        <>
          <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: selectedRowIds,
                onSelect: handleOnSelect,
                onSelectAll: handleOnSelectAll,
              }}
              cellEdit={cellEditFactory(tableConfig.cellEdit)}
              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 AddSuppliesModalTable;
