"use client";

import { ModalFormInput, PurchaseQCInput, PurchaseQcResult, StockInInput, StockInLineEntry, updateStockInLine } from "@/app/api/po/actions";
import { Box, Button, Modal, ModalProps, Stack } from "@mui/material";
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import QcForm from "./QcForm";
import { QcItemWithChecks } from "@/app/api/qc";
import { Check, CurrencyYuanRounded } from "@mui/icons-material";
import { StockInLine } from "@/app/api/po";
import { useSearchParams } from "next/navigation";
import { StockInLineRow } from "./PoInputGrid";
import EscalationForm from "./EscalationForm";
import StockInForm from "./StockInForm";
import PutawayForm from "./PutawayForm";
import { stockInLineStatusMap } from "@/app/utils/formatUtil";

interface CommonProps extends Omit<ModalProps, "children"> {
  setEntries: Dispatch<SetStateAction<StockInLineRow[]>>
  itemDetail: StockInLine & {qcResult?: PurchaseQcResult[]};
  qc?: QcItemWithChecks[];
  warehouse?: any[];
  type: "qc" | "stockIn" | "escalation" | "putaway"
}
interface QcProps extends CommonProps {
  qc: QcItemWithChecks[];
  type: "qc"
} 
interface StockInProps extends CommonProps {
  // naming
  type: "stockIn"
}
interface PutawayProps extends CommonProps {
  // naming
  // warehouse: any[];
  warehouse: any[];
  type: "putaway"
}
interface EscalationProps extends CommonProps {
  // naming
  type: "escalation"
}

type Props = QcProps | StockInProps | EscalationProps | PutawayProps;

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  width: { xs: "80%", sm: "80%", md: "80%" },
};
const PoQcStockInModal: React.FC<Props> = ({
  type,
  setEntries,
  open,
  onClose, 
  itemDetail, 
  qc,
  warehouse,
 }) => {
  console.log(itemDetail)
  const [serverError, setServerError] = useState("");
  const { t } = useTranslation();
  const params = useSearchParams()
  console.log(params.get("id"))
  const [defaultValues, setDefaultValues] = useState({});
  const defaultValue = useMemo(() => {
    // switch (type) {
    //   case "qc":
    //     return {qcResult: itemDetail.qcResult}
    // }
    // return {}
    return {...itemDetail}
  }, [])
  // const formProps = useForm<ModalFormInput>({
  //   defaultValues: defaultValues ? defaultValues : {},
  // });
  const formProps = useForm<ModalFormInput>({
    defaultValues: defaultValue
  });
  const errors = formProps.formState.errors;
  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      onClose?.(...args);
      //   reset();
    },
    [onClose]
  );

  useEffect(() => {
    setDefaultValues({});
  }, []);

  const onSubmit = useCallback<SubmitHandler<ModalFormInput & {}>>(
    async (data, event) => {
      let hasErrors = false;
      console.log(errors);
      console.log(data);
      console.log(itemDetail);
      try {
        // add checking
        // const qty = data.sampleRate
        
        //////////////////////// modify this mess later //////////////////////
        var productionDate = null
        var acceptedQty = null
        if (data.productionDate && data.productionDate.length > 0) {
          productionDate = data.productionDate
        }
        if (data.qcResult) {
          acceptedQty = itemDetail.acceptedQty - data.qcResult.reduce((acc, curr) => acc + curr.failQty, 0)
        }
        const args = {
          id: itemDetail.id,
          purchaseOrderId: parseInt(params.get("id")!!),
          purchaseOrderLineId: itemDetail.purchaseOrderLineId,
          itemId: itemDetail.itemId,
          ...data,
          productionDate: productionDate,
        } as StockInLineEntry & ModalFormInput;
        //////////////////////////////////////////////////////////////////////
        console.log(args)
        // return
        if (hasErrors) {
          setServerError(t("An error has occurred. Please try again later."));
          return false;
        }
        const res = await updateStockInLine(args)
        if (Boolean(res.id)) {
          // update entries
          const newEntries = res.entity as StockInLine[]
          setEntries((prev) => {
            const updatedEntries = [...prev]; // Create a new array
            newEntries.forEach((item) => {
              const index = updatedEntries.findIndex(p => p.id === item.id);
              if (index !== -1) {
                // Update existing item
                updatedEntries[index] = item;
              } else {
                // Add new item
                updatedEntries.push(item);
              }
            });
            return updatedEntries; // Return the new array
          })
          // 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]
  );
  
  const renderSubmitButton = useMemo((): Boolean => {
    if (itemDetail) {
      const status = itemDetail.status
      console.log(status)
      switch (type) {
        case "qc":
          return stockInLineStatusMap[status] === 1
        case "putaway":
          return stockInLineStatusMap[status] === 7
        case "stockIn":
          return stockInLineStatusMap[status] === 6
        default:
          return false; // Handle unexpected type
      }
    } else return false
  }, [type, itemDetail])
  useEffect(() => {
    console.log(renderSubmitButton)
  }, [renderSubmitButton])
  return (
    <>
      <Modal open={open} onClose={closeHandler}>
        <FormProvider {...formProps}>
          <Box
            sx={style}
            component="form"
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            {type === "qc" && <QcForm qc={qc} itemDetail={itemDetail} />}
            {type === "stockIn" && <StockInForm itemDetail={itemDetail} />}
            {type === "escalation" && <EscalationForm itemDetail={itemDetail} />}
            {type === "putaway" && <PutawayForm itemDetail={itemDetail} warehouse={warehouse} />}
            {renderSubmitButton ? (
              <Stack direction="row" justifyContent="flex-end" gap={1}>
                <Button
                  name="submit"
                  variant="contained"
                  startIcon={<Check />}
                  type="submit"
                  //   disabled={submitDisabled}
                >
                  {t("submit")}
                </Button>
              </Stack>
            ) : undefined
            }
          </Box>
        </FormProvider>
      </Modal>
    </>
  );
};
export default PoQcStockInModal;
