import _ from 'lodash';
import { KhovtMasterVtWithRelations, KhovtTransPhieuXuatDetailWithRelations } from 'main/apis/drc/models';
import { useState } from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';
import ToolkitProvider from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit';
import { Link } from 'react-router-dom';
import { Button } from 'reactstrap';
import tableConfig from './table-config';
import AddSuppliesModal from '../add-supplies-modal/add-supplies-modal';

type Props = {
  suppliesList: KhovtTransPhieuXuatDetailWithRelations[];
  handleSuppliesTableChange: (newSuppliesList: KhovtTransPhieuXuatDetailWithRelations[]) => void;
};

function SuppliesStoreExportAddTable({ suppliesList, handleSuppliesTableChange }: Props) {
  // React State
  const [isOpenAddSuppliesModal, setOpenAddSuppliesModal] = useState(false);

  // React function
  const toggleAddSuppliesModal = () => setOpenAddSuppliesModal(!isOpenAddSuppliesModal);

  const handleDeleteSupplies = (suppliesId?: string | null) => {
    handleSuppliesTableChange(suppliesList.filter((item) => item.maVt !== suppliesId));
  };

  const handleAddSuppliesModalConfirmClick = (selectedSuppliesList?: KhovtMasterVtWithRelations[]) => {
    if (!selectedSuppliesList) {
      return;
    }

    // Convert to details
    const newSuppliesList: KhovtTransPhieuXuatDetailWithRelations[] = [];
    for (const selectedSupplies of selectedSuppliesList) {
      const { maVt, tenVt } = selectedSupplies;
      newSuppliesList.push({
        maVt,
        tenVt,
        maLo: 'dummy',
        nguonGoc: 'dummy',
        soLuongThucTe: 0,
        soLuongYeuCau: 0,
        tonKho: 0,
      });
    }

    // Merge and deduplicate
    const updatedSuppliesList = _.unionBy(suppliesList, newSuppliesList, 'maVt');

    handleSuppliesTableChange(updatedSuppliesList);
    toggleAddSuppliesModal();
  };

  return (
    <>
      <ToolkitProvider
        data={suppliesList}
        keyField="id"
        columns={[
          ...tableConfig.columns,
          {
            dataField: 'action',
            isDummyField: true,
            text: 'Thao tác',
            formatter: (_: any, row: KhovtTransPhieuXuatDetailWithRelations) => {
              return (
                <Link
                  to="#"
                  onClick={(e) => {
                    e.preventDefault();
                    handleDeleteSupplies(row.maVt);
                  }}>
                  &lt;Xóa&gt;
                </Link>
              );
            },
          },
        ]}>
        {(props: any) => (
          <>
            <div className="d-flex justify-content-end pb-4">
              <Button className="btn-neutral" onClick={toggleAddSuppliesModal}>
                Thêm vật tư
              </Button>
            </div>
            <div className="table-responsive">
              <BootstrapTable
                {...props.baseProps}
                bootstrap4={true}
                bordered={false}
                cellEdit={cellEditFactory(tableConfig.cellEdit)}
                noDataIndication={() => <div className="text-center">Chưa có vật tư nào</div>}
              />
            </div>
            <AddSuppliesModal
              isOpen={isOpenAddSuppliesModal}
              toggle={toggleAddSuppliesModal}
              handleConfirmClick={handleAddSuppliesModalConfirmClick}
            />
          </>
        )}
      </ToolkitProvider>
    </>
  );
}

export default SuppliesStoreExportAddTable;
