import {
  useKhovtTransPhieuXuatControllerCount,
  useKhovtTransPhieuXuatControllerFind,
} from 'main/apis/drc/endpoints/khovt-trans-phieu-xuat-controller/khovt-trans-phieu-xuat-controller';
import { KhovtTransPhieuXuatWithRelations } from 'main/apis/drc/models';
import BasicTemplate from 'main/components/templates/basic-template';
import { Page } from 'main/constants';
import { useState } from 'react';
import { TableChangeState, TableChangeType } from 'react-bootstrap-table-next';
import { Card, CardBody, CardHeader, Container, Row } from 'reactstrap';
import SuppliesStoreExportFilter, {
  ExportFilter,
} from './sub-components/supplies-store-export-filter/supplies-store-export-filter';
import SuppliesStoreExportTable, {
  ExportTable,
} from './sub-components/supplies-store-export-table/supplies-store-export-table';

const getSuppliesExportBillsParams = (filter: ExportFilter, table: ExportTable) => {
  const where = getSuppliesExportBillsCountParams(filter).where;
  const { page, sizePerPage, sortField, sortOrder } = table;

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

const getSuppliesExportBillsCountParams = (filter: ExportFilter) => {
  const { startDate, endDate, importStore, exportStore, exportBillNo, exportStatus } = filter;
  return {
    where: {
      khoNhap: importStore && importStore !== '-1' ? importStore : undefined,
      khoXuat: exportStore && exportStore !== '-1' ? exportStore : undefined,
      and:
        startDate && endDate
          ? [{ ngayXuat: { gte: startDate.toDate() } }, { ngayXuat: { lte: endDate.toDate() } }]
          : undefined,
      soPhieu: exportBillNo ? exportBillNo : undefined,
      status: exportStatus && exportStatus !== '-1' ? exportStatus : undefined,
    },
  };
};

function SuppliesStoreExportList() {
  // React State
  const [filter, setFilter] = useState<ExportFilter>({
    exportStore: '',
    importStore: '',
    exportBillNo: '',
    exportStatus: '',
  });
  const [table, setTable] = useState<ExportTable>({
    page: 1,
    sizePerPage: 2,
  });

  // React Query
  const { data: suppliesExportBills, isLoading: suppliesExportBillsIsLoading } = useKhovtTransPhieuXuatControllerFind(
    getSuppliesExportBillsParams(filter, table),
  );

  const { data: suppliesExportBillsCount, isLoading: suppliesExportBillsCountIsLoading } =
    useKhovtTransPhieuXuatControllerCount(getSuppliesExportBillsCountParams(filter));

  // React Function
  const handleSearchClick = (newFilter: ExportFilter) => {
    setFilter(newFilter);

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

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

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

  return (
    <BasicTemplate pageTitle={Page.SUPPLIES_STORE_EXPORT_LIST.TITLE} pageName={Page.SUPPLIES_STORE_EXPORT_LIST.NAME}>
      <Container className="mt--6" fluid>
        <Row>
          <div className="col">
            <Card>
              <CardHeader>
                <h3>TỔNG HỢP XUẤT VẬT TƯ</h3>
              </CardHeader>
              <CardBody>
                <SuppliesStoreExportFilter filter={filter} handleSearchClick={handleSearchClick} />
                <hr />
                <SuppliesStoreExportTable
                  data={suppliesExportBills}
                  dataIsLoading={suppliesExportBillsIsLoading}
                  dataCount={suppliesExportBillsCount?.count}
                  dataCountIsLoading={suppliesExportBillsCountIsLoading}
                  tableState={table}
                  handleTableStateChange={handleTableChange}
                />
              </CardBody>
            </Card>
          </div>
        </Row>
      </Container>
    </BasicTemplate>
  );
}

export default SuppliesStoreExportList;
