"use client";

import {
  Box,
  Button,
  Grid,
  Modal,
  ModalProps,
  Stack,
  Typography,
} from "@mui/material";
import { useCallback, useEffect, useMemo, useState } from "react";
import { GridRowModesModel, GridRowSelectionModel } from "@mui/x-data-grid";
import ReactQrCodeScanner, {
  ScannerConfig,
} from "../ReactQrCodeScanner/ReactQrCodeScanner";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import {
  fetchStockInLineInfo,
  ModalFormInput,
  StockInLineEntry,
  updateStockInLine,
} from "@/app/api/po/actions";
import PutAwayForm from "./PutAwayForm"; 
import { StockInLine } from "@/app/api/po";
import { WarehouseResult } from "@/app/api/warehouse";
import { QrCodeInfo } from "@/app/api/qrcode";
import { Check } from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "next/navigation";
import { useQrCodeScannerContext } from "../QrCodeScannerProvider/QrCodeScannerProvider";

interface Props extends Omit<ModalProps, "children"> {
  warehouse: WarehouseResult[];
}
const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  width: "auto",
};
const QrModal: React.FC<Props> = ({ open, onClose, warehouse }) => {
  const { t } = useTranslation("purchaseOrder");
  const [serverError, setServerError] = useState("");
  const params = useSearchParams();
  const formProps = useForm<ModalFormInput>({
    defaultValues: {
      status: "received",
      // acceptedQty
      // ...itemDetail,
    },
  });
  const errors = formProps.formState.errors;
  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      onClose?.(...args);
      setItemDetail(undefined);
      setStockInLineId(undefined);
      //   reset();
    },
    [onClose],
  );
  const [stockInLineId, setStockInLineId] = useState<number>();
  const scannerConfig = useMemo<ScannerConfig>(
    () => ({
      onUpdate: (err, result) => {
        if (result) {
          const data: QrCodeInfo = JSON.parse(result.getText());
          console.log(data);
          if (data.stockInLineId) {
            console.log("still got in");
            console.log(data.stockInLineId);
            setStockInLineId(data.stockInLineId);
          }
        } else return;
      },
    }),
    [],
  );

  // QR Code Scanner
  const scanner = useQrCodeScannerContext();
  useEffect(() => {
    if (open && !scanner.isScanning) {
      scanner.startScan();
    } else if (!open && scanner.isScanning) {
      scanner.stopScan();
    }
  }, [open]);

  useEffect(() => {
    if (scanner.values.length > 0 && !Boolean(itemDetail)) {
      console.log(scanner.values[0]);
      const data: QrCodeInfo = JSON.parse(scanner.values[0]);
      console.log(data);
      if (data.stockInLineId) {
        console.log("still got in");
        console.log(data.stockInLineId);
        setStockInLineId(data.stockInLineId);
      }
      scanner.resetScan();
    }
  }, [scanner.values]);

  const [itemDetail, setItemDetail] = useState<StockInLine>();
  const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
  const [rowSelectionModel, setRowSelectionModel] = useState<GridRowSelectionModel>([]);
  const [disabledSubmit, setDisabledSubmit] = useState(false);
  const [unavailableText, setUnavailableText] = useState<string | undefined>(
    undefined,
  );

  const fetchStockInLine = useCallback(
    async (stockInLineId: number) => {
      setUnavailableText(undefined);
      const res = await fetchStockInLineInfo(stockInLineId);
      if (res.status.toLowerCase() === "received") {
        console.log(res.acceptedQty);
        formProps.setValue("acceptedQty", res.acceptedQty);
        setDisabledSubmit(false);
        setItemDetail(res);
      } else if (res.status.toLowerCase() === "completed") {
        setDisabledSubmit(true);
      } else {
        //
        setUnavailableText("Item Not Available");
        setDisabledSubmit(true);
      }
    },
    [formProps, itemDetail, fetchStockInLineInfo],
  );

  useEffect(() => {
    if (stockInLineId) fetchStockInLine(stockInLineId);
  }, [stockInLineId]);

  const onSubmit = useCallback<SubmitHandler<ModalFormInput>>(
    async (data, event) => {
      const hasErrors = false;
      console.log("errors");
      console.log(errors);
      console.log("data");
      console.log(data);
      console.log("itemDetail");
      console.log(itemDetail);
      try {
        // add checking
        // const qty = data.sampleRate

        //////////////////////// modify this mess later //////////////////////
        const args = {
          id: itemDetail?.id,
          purchaseOrderId: parseInt(params.get("id")!),
          purchaseOrderLineId: itemDetail?.purchaseOrderLineId,
          itemId: itemDetail?.itemId,
          acceptedQty: data.acceptedQty,
          warehouseId: data.warehouseId,
          status: data.status,
          // ...data,
          //   productionDate: productionDate,
        } as StockInLineEntry & ModalFormInput;
        //////////////////////////////////////////////////////////////////////
        console.log(args);
        // return
        if (hasErrors) {
          setServerError(t("An error has occurred. Please try again later."));
          return false;
        }
        // return;
        const res = await updateStockInLine(args);
        if (Boolean(res.id)) {
          // update entries
          console.log(res);
          // add loading
          closeHandler({}, "backdropClick");
        }
        console.log(res);
        // if (res)
      } catch (e) {
        // server error
        setServerError(t("An error has occurred. Please try again later."));
        console.log(e);
      }
    },
    [t, itemDetail],
  );

  return (
    <FormProvider {...formProps}>
      <Modal open={open} onClose={closeHandler}>
        <Box
          sx={style}
          component="form"
          onSubmit={formProps.handleSubmit(onSubmit)}
        >
          <Grid container xs={12}>
            <Grid item xs={12}>
              {itemDetail != undefined ? (
                unavailableText != undefined ? (
                  <Typography variant="h4" marginInlineEnd={2}>
                    {unavailableText}
                  </Typography>
                ) : (
                  <>
                    <PutAwayForm
                      itemDetail={itemDetail}
                      warehouse={warehouse}
                      disabled={false}
                      setRowModesModel={setRowModesModel}
                      setRowSelectionModel={setRowSelectionModel}
                    />
                    <Stack direction="row" justifyContent="flex-end" gap={1}>
                      <Button
                        name="submit"
                        variant="contained"
                        startIcon={<Check />}
                        type="submit"
                        disabled={disabledSubmit}
                      >
                        {t("submit")}
                      </Button>
                    </Stack>
                  </>
                )
              ) : (
                // <ReactQrCodeScanner scannerConfig={scannerConfig} />
                <Typography variant="h4">
                  {t(
                    "Will start binding procedure after scanning item qr code.",
                  )}
                </Typography>
              )}
            </Grid>
          </Grid>
        </Box>
      </Modal>
    </FormProvider>
  );
};

export default QrModal;
