import {
  useKhovtMasterVtControllerCount,
  useKhovtMasterVtControllerFind,
} from 'main/apis/drc/endpoints/khovt-master-vt-controller/khovt-master-vt-controller';
import { KhovtMasterVtWithRelations } from 'main/apis/drc/models';
import { useState } from 'react';
import { TableChangeState, TableChangeType } from 'react-bootstrap-table-next';
import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
import AddSuppliesModalFilter, { SuppliesFilter } from './add-supplies-modal-filter';
import AddSuppliesModalTable, { ExportTable } from './supplies-store-export-table/add-supplies-modal-table';

const getSuppliesParams = (filter: SuppliesFilter, table: ExportTable) => {
  const where = getSuppliesCountParams(filter).where;
  const { page, sizePerPage, sortField, sortOrder } = table;

  return {
    filter: {
      offset: (page - 1) * sizePerPage,
      limit: sizePerPage,
      order: sortField ? `${sortField} ${sortOrder?.toUpperCase()}` : undefined,
      where,
    },
  };
};

const getSuppliesCountParams = (filter: SuppliesFilter) => {
  const { suppliesGroup, suppliesCode, batch } = filter;
  return {
    where: {
      maNhom: suppliesGroup && suppliesGroup !== '-1' ? suppliesGroup : undefined,
      maVt: suppliesCode ? suppliesCode : undefined,
      maLo: batch && batch !== '-1' ? batch : undefined,
    },
  };
};

type Props = {
  isOpen: boolean;
  toggle: () => void;
  handleConfirmClick: (selectedSuppliesList?: KhovtMasterVtWithRelations[]) => void;
};

function AddSuppliesModal({ isOpen, toggle, handleConfirmClick }: Props) {
  // React State
  const [filter, setFilter] = useState<SuppliesFilter>({
    suppliesGroup: '',
    suppliesCode: '',
    batch: '',
  });
  const [table, setTable] = useState<ExportTable>({
    page: 1,
    sizePerPage: 10,
  });

  // React Query
  const { data: supplies, isLoading: suppliesIsLoading } = useKhovtMasterVtControllerFind(
    getSuppliesParams(filter, table),
  );

  const { data: suppliesCount, isLoading: suppliesCountIsLoading } = useKhovtMasterVtControllerCount(
    getSuppliesCountParams(filter),
  );

  // React fucnction
  const handleSearchClick = (newFilter: SuppliesFilter) => {
    setFilter(newFilter);

    // Reset table state
    setTable({ ...table, page: 1, sortField: undefined, sortOrder: undefined });
  };

  const handleTableChange = (_: TableChangeType, newState: TableChangeState<KhovtMasterVtWithRelations>) => {
    const { page, sizePerPage, sortField, sortOrder } = newState;

    // Update state
    setTable({ ...table, page, sizePerPage, sortOrder, sortField });
  };

  const handleSelectedRowsChange = (newSelectedRows: KhovtMasterVtWithRelations[]) => {
    setTable({ ...table, selectedRows: newSelectedRows });
  };

  return (
    <Modal isOpen={isOpen} toggle={toggle} centered fade={false} size="xl">
      <ModalHeader toggle={toggle}>Thêm vật tư</ModalHeader>
      <ModalBody>
        <AddSuppliesModalFilter filter={filter} handleSearchClick={handleSearchClick} />
        <hr />
        <AddSuppliesModalTable
          data={supplies}
          dataIsLoading={suppliesIsLoading}
          dataCount={suppliesCount?.count}
          dataCountIsLoading={suppliesCountIsLoading}
          tableState={table}
          handleTableStateChange={handleTableChange}
          handleSelectedRowsChange={handleSelectedRowsChange}
        />
      </ModalBody>
      <ModalFooter className="justify-content-between">
        <Button color="primary" onClick={() => handleConfirmClick(table.selectedRows)}>
          Thêm
        </Button>
        <Button color="secondary" onClick={toggle}>
          Hủy
        </Button>
      </ModalFooter>
    </Modal>
  );
}

export default AddSuppliesModal;
