import { QcItemWithChecks } from "@/app/api/qc";
import useUploadContext from "../UploadProvider/useUploadContext";
import {
  PickOrderApprovalInput,
  PickOrderQcInput,
  updateStockOutLine,
  UpdateStockOutLine,
} from "@/app/api/pickOrder/actions";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import QcContent from "./QcContent";
import { Box, Button, Modal, ModalProps, Stack } from "@mui/material";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Check } from "@mui/icons-material";
import { StockOutLine } from "@/app/api/pickOrder";
import dayjs from "dayjs";
import { INPUT_DATE_FORMAT, OUTPUT_TIME_FORMAT } from "@/app/utils/formatUtil";
import ApprovalContent from "./ApprovalContent";

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  //   overflow: "scroll",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  display: "block",
  width: { xs: "60%", sm: "60%", md: "60%" },
};

interface Props extends Omit<ModalProps, "children"> {
  // qc: QcItemWithChecks[];
  approvalDefaultValues: StockOutLine & PickOrderApprovalInput;
  disabled: boolean;
}

const ApprovalForm: React.FC<Props> = ({
  // qc,
  approvalDefaultValues,
  disabled,
  open,
  onClose,
}) => {
  const { setIsUploading } = useUploadContext();
  const { t } = useTranslation("pickOrder");
  const formProps = useForm<PickOrderApprovalInput>({
    defaultValues: {
      allowQty: approvalDefaultValues.qty,
      rejectQty: 0,
      status: approvalDefaultValues.status,
    },
  });

  const errors = formProps.formState.errors;
  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      onClose?.(...args);
      //   reset();
    },
    [onClose],
  );

  const onSubmit = useCallback<SubmitHandler<PickOrderApprovalInput>>(
    async (data, event) => {
      console.log(data);
      // checking later
      // post
      const hasError = false;
      if (data.allowQty + data.rejectQty != approvalDefaultValues.qty) {
        formProps.setError("allowQty", {
          message: "illegal qty",
          type: "required",
        });
        formProps.setError("rejectQty", {
          message: "illegal qty",
          type: "required",
        });
      }
      if (hasError) {
        return;
      }
      const postData: UpdateStockOutLine = {
        id: approvalDefaultValues.id,
        itemId: approvalDefaultValues.itemId,
        pickOrderLineId: approvalDefaultValues.pickOrderLineId,
        qty: data.allowQty, //allow qty
        status: data.status,
        // pickTime: dayjs().format(`${INPUT_DATE_FORMAT} ${OUTPUT_TIME_FORMAT}`),
      };
      console.log(postData);
      // return;
      const res = await updateStockOutLine(postData);
      if (res) {
        console.log(res);
        closeHandler({}, "backdropClick");
      } else {
        console.log(res);
        console.log("bug la");
      }
    },
    [t],
  );
  return (
    <>
      <FormProvider {...formProps}>
        <Modal open={open} onClose={closeHandler}>
          <Box
            sx={style}
            component="form"
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            <ApprovalContent
              approvalDefaultValues={approvalDefaultValues}
              disabled={disabled}
            />
            <Stack direction="row" justifyContent="flex-end" gap={1}>
              {!disabled ? (
                <Button
                  name="submit"
                  variant="contained"
                  startIcon={<Check />}
                  type="submit"
                >
                  {t("submit")}
                </Button>
              ) : undefined}
            </Stack>
          </Box>
        </Modal>
      </FormProvider>
    </>
  );
};
export default ApprovalForm;
