import { Formik } from 'formik';
import { useKhovtTransPhieuXuatControllerCreate } from 'main/apis/drc/endpoints/khovt-trans-phieu-xuat-controller/khovt-trans-phieu-xuat-controller';
import { KhovtTransPhieuXuatDetailWithRelations } from 'main/apis/drc/models';
import BasicTemplate from 'main/components/templates/basic-template';
import { Page } from 'main/constants';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Card, CardBody, CardFooter, CardHeader, Container, Row } from 'reactstrap';
import * as Yup from 'yup';
import SaveExportBillModal from './sub-components/save-export-bill-modal';
import SuppliesStoreExportAddInfo from './sub-components/supplies-store-export-add-info';
import SuppliesStoreExportAddTable from './sub-components/supplies-store-export-add-table/supplies-store-export-add-table';

function SuppliesStoreExportAdd() {
  // React Router
  const navigate = useNavigate();

  // React State
  const [suppliesStoreExportDetails, setSuppliesStoreExportDetails] = useState<
    KhovtTransPhieuXuatDetailWithRelations[]
  >([]);
  const [isOpenSaveModal, setOpenSaveModal] = useState(false);

  // React Query
  const {
    isPending: createdSuppliesExportBillIsPeding,
    isError: createdSuppliesExportBillIsError,
    mutateAsync: createdSuppliesExportBillMutateAsync,
  } = useKhovtTransPhieuXuatControllerCreate();

  // React function
  const handleSuppliesTableChange = (newSuppliesList: KhovtTransPhieuXuatDetailWithRelations[]) => {
    setSuppliesStoreExportDetails(newSuppliesList);
  };

  const toggleSaveModal = () => setOpenSaveModal(!isOpenSaveModal);

  const handleSaveConfirmClick = async (info: {
    ghiChu: string;
    khoNhap: string;
    khoXuat: string;
    lyDoXuat: string;
    ngayXuat: string;
    nguoiTaoPhieu: string;
    soPhieu: string;
    status: string;
    thongTinCanhBao: string;
  }) => {
    toggleSaveModal();
    const newSuppliesExportBill = await createdSuppliesExportBillMutateAsync({
      data: {
        ...info,
        details: suppliesStoreExportDetails,
      },
    });
    if (createdSuppliesExportBillIsError) {
      navigate(Page.SYSTEM_ERROR.PATH);
    } else {
      navigate(`${Page.SUPPLIES_STORE_EXPORT_DETAIL.PATH.replace(':id', String(newSuppliesExportBill.id))}`);
    }
  };

  return (
    <BasicTemplate pageTitle={Page.SUPPLIES_STORE_EXPORT_ADD.TITLE} pageName={Page.SUPPLIES_STORE_EXPORT_ADD.NAME}>
      <Container className="mt--6" fluid>
        <Row>
          <div className="col">
            <Formik
              initialValues={{
                ghiChu: '',
                khoNhap: '',
                khoXuat: '',
                lyDoXuat: '',
                ngayXuat: '',
                nguoiTaoPhieu: '',
                soPhieu: '',
                status: '',
                thongTinCanhBao: '',
              }}
              validationSchema={Yup.object().shape({
                soPhieu: Yup.string().required('Trường này là bắt buộc'),
                khoXuat: Yup.string().required('Trường này là bắt buộc'),
                khoNhap: Yup.string().required('Trường này là bắt buộc'),
                nguoiTaoPhieu: Yup.string().required('Trường này là bắt buộc'),
                ngayXuat: Yup.string().required('Trường này là bắt buộc'),
              })}
              onSubmit={() => {
                // do nothing
              }}>
              {(formikProps) => (
                <Card>
                  <CardHeader>
                    <h3 className="mb-0 text-center">SỐ PHIẾU XUẤT</h3>
                  </CardHeader>
                  <CardBody>
                    <SuppliesStoreExportAddInfo formikProps={formikProps} />
                    <SuppliesStoreExportAddTable
                      suppliesList={suppliesStoreExportDetails}
                      handleSuppliesTableChange={handleSuppliesTableChange}
                    />
                    <SaveExportBillModal
                      isOpen={isOpenSaveModal}
                      toggle={toggleSaveModal}
                      handleConfirmClick={() => handleSaveConfirmClick(formikProps.values)}
                    />
                  </CardBody>
                  <CardFooter>
                    <div className="d-flex justify-content-between px-4 pb-1">
                      <Button className="btn-dark" onClick={() => navigate(Page.SUPPLIES_STORE_EXPORT_LIST.PATH)}>
                        Thoát
                      </Button>
                      <div>
                        <Button
                          color="primary"
                          onClick={toggleSaveModal}
                          disabled={!formikProps.dirty || !formikProps.isValid}>
                          Lưu
                        </Button>
                        <Button color="primary">Xuất hàng</Button>
                      </div>
                    </div>
                  </CardFooter>
                </Card>
              )}
            </Formik>
          </div>
        </Row>
      </Container>
    </BasicTemplate>
  );
}

export default SuppliesStoreExportAdd;
