"use client";
import { QcItemWithChecks, QcData } from "@/app/api/qc";
import {
  Autocomplete,
  Box,
  Button,
  Divider,
  Grid,
  Modal,
  ModalProps,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  TextField,
  Typography,
} from "@mui/material";
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import { StockInLineRow } from "../PoDetail/PoInputGrid";
import { useTranslation } from "react-i18next";
import StockInForm from "../StockIn/StockInForm";
import QcComponent from "./QcComponent";
import PutAwayForm from "../PoDetail/PutAwayForm";
import { GridRowModes, GridRowSelectionModel, useGridApiRef } from "@mui/x-data-grid";
import {msg, submitDialogWithWarning} from "../Swal/CustomAlerts";
import { INPUT_DATE_FORMAT, arrayToDateString, dayjsToDateTimeString } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import { fetchPoQrcode } from "@/app/api/pdf/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { PrinterCombo } from "@/app/api/settings/printer";
import { EscalationResult } from "@/app/api/escalation";
import { SessionWithTokens } from "@/config/authConfig";
import { GridRowModesModel } from "@mui/x-data-grid";
import { isEmpty } from "lodash";
import { EscalationCombo } from "@/app/api/user";
import { truncateSync } from "fs";
import { ModalFormInput, StockInLineInput, StockInLine, StockInStatus } from "@/app/api/stockIn";
import { StockInLineEntry, updateStockInLine, printQrCodeForSil, PrintQrCodeForSilRequest } from "@/app/api/stockIn/actions";
import { fetchStockInLineInfo } from "@/app/api/stockIn/actions";
import FgStockInForm from "../StockIn/FgStockInForm";
import LoadingComponent from "../General/LoadingComponent";
import { printFGStockInLabel, PrintFGStockInLabelRequest, fetchFGStockInLabel } from "@/app/api/jo/actions";
import { fetchItemForPutAway } from "@/app/api/stockIn/actions";
import { fetchWarehouseListClient } from "@/app/api/warehouse/client";
const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  display: "block",
  width: "min(1280px, calc(100vw - 48px))",
  maxWidth: "1280px",
  height: "min(900px, calc(100vh - 48px))",
  maxHeight: "calc(100vh - 48px)",
};
interface CommonProps extends Omit<ModalProps, "children" | "onClose"> {
  // itemDetail: StockInLine & { qcResult?: PurchaseQcResult[] } & { escResult?: EscalationResult[] } | undefined;
  inputDetail: StockInLineInput | undefined;
  session: SessionWithTokens | null;
  warehouse?: any[];
  printerCombo: PrinterCombo[];
  onClose: (updatedStockInLine?: StockInLine) => void;
  skipQc?: Boolean;
  printSource?: "stockIn" | "productionProcess";
  uiMode?: "default" | "dashboard" | "productionProcess";
}
interface Props extends CommonProps {
  // itemDetail: StockInLine & { qcResult?: PurchaseQcResult[] } & { escResult?: EscalationResult[] };
}

const QcStockInModal: React.FC<Props> = ({
  open,
  onClose,
  // itemDetail,
  inputDetail,
  session,
  warehouse,
  printerCombo,
  skipQc = false,
  printSource = "stockIn",
  uiMode = "default",
}) => {
  const {
    t,
    i18n: { language },
  } = useTranslation("purchaseOrder");
  const useCompactFields = useMemo(() => {
    return uiMode === "dashboard" || uiMode === "productionProcess";
  }, [uiMode]);
  
  const useDenseQcLayout = useMemo(() => {
    return uiMode === "productionProcess";
  }, [uiMode]);
  const [stockInLineInfo, setStockInLineInfo] = useState<StockInLine>();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  // const [skipQc, setSkipQc] = useState<Boolean>(false);
  // const [viewOnly, setViewOnly] = useState(false);

  const [itemLocationCode, setItemLocationCode] = useState<string | null>(null);
  const printerStorageKey = useMemo(
    () => `qcStockInModal_selectedPrinterId_${session?.id ?? "guest"}`,
    [session?.id],
  );
  const labelPrinterCombo = useMemo(
    () => (printerCombo || []).filter((p) => p.type === "Label"),
    [printerCombo],
  );
  const getDefaultPrinter = useMemo(() => {
    if (!printerCombo.length) return undefined;
    if (typeof window === "undefined") return printerCombo[0];

    const savedId = sessionStorage.getItem(printerStorageKey);
    const matched = savedId ? printerCombo.find(p => p.id === Number(savedId)) : undefined;
    return matched ?? printerCombo[0];
  }, [printerCombo, printerStorageKey]);
  const [selectedPrinter, setSelectedPrinter] = useState(labelPrinterCombo[0]);
  const [printQty, setPrintQty] = useState(1);
  const [tabIndex, setTabIndex] = useState(0);

  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  const fetchStockInLineData = useCallback(
    async (stockInLineId: number) => {
      try {
        const res = await fetchStockInLineInfo(stockInLineId);
        if (res) {
          console.log("%c Fetched Stock In Line: ", "color:orange", res);
          console.log("%c [QC] itemId in response:", "color:yellow", res.itemId);
          console.log("%c [QC] locationCode in response:", "color:yellow", res.locationCode);
          // 如果 res 中没有 itemId，检查是否有其他方式获取
          if (!res.itemId) {
            console.warn("%c [QC] Warning: itemId is missing in response!", "color:red");
          }
          setStockInLineInfo({...inputDetail, ...res, expiryDate: res.expiryDate});
        } else throw("Result is undefined");
      } catch (e) {
        console.log("%c Error when fetching Stock In Line: ", "color:red", e);
        console.log("%c Error details: ", "color:red", {
          message: e instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined
        });
        alert("Something went wrong, please retry");
        closeHandler({}, "backdropClick");
      }
    },[fetchStockInLineInfo, inputDetail]
  );

  // Fetch info if id is input
  useEffect(() => {
    setIsLoading(true);
    setIsSubmitting(false);
    if (inputDetail && open) {
      console.log("%c Opened Modal with input:", "color:yellow", inputDetail);
      if (inputDetail.id) {
        const id = inputDetail.id;
        fetchStockInLineData(id);
      }
    }
  }, [open]);
  useEffect(() => {
    // 如果后端已经在 StockInLine 中返回了 locationCode，直接使用
    if (stockInLineInfo?.locationCode) {
      setItemLocationCode(stockInLineInfo.locationCode);
      console.log("%c [QC] item LocationCode from API:", "color:cyan", stockInLineInfo.locationCode);
      return;
    }
  
    // 如果没有 locationCode，尝试从 itemId 获取（向后兼容）
    const loadItemLocationCode = async () => {
      if (!stockInLineInfo?.itemId) return;
    
      try {
        const itemResult = await fetchItemForPutAway(stockInLineInfo.itemId);
        const item = itemResult.item;
    
        const locationCode = item.LocationCode || item.locationCode || null;
        setItemLocationCode(locationCode);
        console.log("%c [QC] item LocationCode from fetchItemForPutAway:", "color:cyan", locationCode);
      } catch (error) {
        console.error("Error fetching item to get LocationCode in QC:", error);
        setItemLocationCode(null);
      }
    };
  
    if (stockInLineInfo && stockInLineInfo.status !== StockInStatus.REJECTED) {
      loadItemLocationCode();
    }
  }, [stockInLineInfo]);
  // Make sure stock in line info is fetched
  useEffect(() => {
    if (stockInLineInfo) {
      if (stockInLineInfo.id) {
        if (isLoading) {
          formProps.reset({
            ...defaultNewValue
          });
          console.log("%c Modal loaded successfully", "color:lime");
          setIsLoading(false);
        }
      }
    }
    
  }, [stockInLineInfo]);

  const defaultNewValue = useMemo(() => {
    const d = stockInLineInfo;
    if (d !== undefined) {
      // console.log("%c sil info", "color:yellow", d )
      return (
        {
          ...d,
          // status: d.status ?? "pending",
          productionDate: d.productionDate ? arrayToDateString(d.productionDate, "input") : dayjs().format(INPUT_DATE_FORMAT),
          expiryDate: d.expiryDate ? (Array.isArray(d.expiryDate) ? arrayToDateString(d.expiryDate, "input") : d.expiryDate) : undefined,
          receiptDate: d.receiptDate ? arrayToDateString(d.receiptDate, "input")
          : dayjs().add(0, "month").format(INPUT_DATE_FORMAT),
          acceptQty: d.status != StockInStatus.REJECTED ? (d.acceptedQty ?? d.receivedQty ?? d.demandQty) : 0,
          // escResult: (d.escResult && d.escResult?.length > 0) ? d.escResult : [],
          // qcResult: (d.qcResult && d.qcResult?.length > 0) ? d.qcResult : [],//[...dummyQCData],
          warehouseId: d.defaultWarehouseId ?? 1141,
          putAwayLines: d.putAwayLines?.map((line) => ({...line, printQty: 1, _isNew: false, _disableDelete: true})) ?? [],
        } as ModalFormInput
      )
    } return undefined
  }, [stockInLineInfo])

// const [qcItems, setQcItems] = useState(dummyQCData)
  const formProps = useForm<ModalFormInput>({
    defaultValues: {
      ...defaultNewValue,
    },
  });

  const closeWithResult = useCallback(
    (updatedStockInLine?: StockInLine) => {
      setStockInLineInfo(undefined);
      formProps.reset({});
      onClose?.(updatedStockInLine);
    },
    [onClose],
  );

  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    () => {
      setStockInLineInfo(undefined);
      formProps.reset({});
      onClose?.();
    },
    [onClose],
  );
  
  const isPutaway = () => {
    if (stockInLineInfo) {
      const status = stockInLineInfo.status;
      return status == "received";

    } else return false;
  };

  // Get show putaway
  const showPutaway = useMemo(() => {
    if (stockInLineInfo) {
      const status = stockInLineInfo.status;
      return status !== StockInStatus.PENDING && status !== StockInStatus.ESCALATED && status !== StockInStatus.REJECTED;
    }
    return false;
  }, [stockInLineInfo]);

  // Get is view only
  const viewOnly = useMemo(() => {
    if (stockInLineInfo) {
      if (stockInLineInfo.status) {
        const status = stockInLineInfo.status;
        const isViewOnly = status.toLowerCase() == StockInStatus.COMPLETED
        || status.toLowerCase() == StockInStatus.PARTIALLY_COMPLETED // TODO update DB
        || status.toLowerCase() == StockInStatus.REJECTED
        || (status.toLowerCase() == StockInStatus.ESCALATED && session?.id != stockInLineInfo.handlerId)
        if (showPutaway) { setTabIndex(1); } else { setTabIndex(0); }
        return isViewOnly;
      }
    }
    return true;
  }, [stockInLineInfo])

  const [openPutaway, setOpenPutaway] = useState(false);
  const onOpenPutaway = useCallback(() => {
    
    setOpenPutaway(true);
  }, []);
  const onClosePutaway = useCallback(() => {
    setOpenPutaway(false);
  }, []);

  // Stock In submission handler
  const onSubmitStockIn = useCallback<SubmitHandler<ModalFormInput>>(
    async (data, event) => {
      console.log("Stock In Submission:", event!.nativeEvent);
      // Extract only stock-in related fields
      const stockInData = {
        //    quantity: data.quantity,
        //    receiptDate: data.receiptDate,
        //    batchNumber: data.batchNumber,
        //    expiryDate: data.expiryDate,
        //    warehouseId: data.warehouseId,
        //    location: data.location,
        //    unitCost: data.unitCost,
        data: data,
        // Add other stock-in specific fields from your form
      };
      console.log("Stock In Data:", stockInData);
      // Handle stock-in submission logic here
      // e.g., call API, update state, etc.
    },
    [],
  );

  // QC submission handler
  const onSubmitErrorQc = useCallback<SubmitErrorHandler<ModalFormInput>>(
    async (data, event) => {
      console.log("Error", data);
    }, []
  );

  // QC submission handler
  const onSubmitQc = useCallback<SubmitHandler<ModalFormInput>>(
    async (data, event) => {
      console.log("QC Submission:", event!.nativeEvent);
      console.log("Validating:", data.qcResult);
      // TODO: Move validation into QC page

      // if (errors.length > 0) {
      //   alert(`未完成品檢: ${errors.map((err) => err[1].message)}`);
      //   return;
      // }

      // Get QC data from the shared form context
      const qcAcceptLocal = data.qcDecision == 1;
      
      // const qcAccept = data.qcAccept;
      let acceptQtyLocal = Number(data.acceptQty);
      const qcResultsLocal = data.qcResult?.filter((qc) => qc.escalationLogId === undefined) || []; // Remove old QC data
      // const qcResults = data.qcResult as PurchaseQcResult[]; // qcItems;
      // const qcResults = viewOnly? data.qcResult as PurchaseQcResult[] : qcItems;
      
      // Validate QC data
      const validationErrors : string[] = [];
      

      // Check if failed items have failed quantity
      const failedItemsWithoutQty = qcResultsLocal.filter(item => 
        item.qcPassed === false && (!item.failQty || item.failQty <= 0)
      );
      if (failedItemsWithoutQty.length > 0) {
        validationErrors.push(`${t("Failed items must have failed quantity")}`);
        // validationErrors.push(`${t("Failed items must have failed quantity")}: ${failedItemsWithoutQty.map(item => item.code).join(', ')}`);
      }

      // Check if QC accept decision is made
      if (data.qcDecision === undefined) {
      // if (qcAccept === undefined) {
        validationErrors.push(t("QC decision is required"));
      }

      // Check if accept quantity is valid
      if (data.qcDecision == 2) {
        acceptQtyLocal = 0;
      } else {
        if (acceptQtyLocal === undefined || acceptQtyLocal <= 0) {
          validationErrors.push("Accept quantity must be greater than 0");
        }
      }
      // Check if dates are input
      // if (data.productionDate === undefined || data.productionDate == null) {
      //   alert("請輸入生產日期！");
      //   return;
      // }
      if (data.expiryDate === undefined || data.expiryDate == null) {
        alert("請輸入到期日！");
        return;
      }
      if (!qcResultsLocal.every((qc) => qc.qcPassed) && qcAcceptLocal  && stockInLineInfo?.status != StockInStatus.ESCALATED) {  //TODO: fix it please!
        validationErrors.push("有不合格檢查項目，無法收貨！");
        // submitDialogWithWarning(() => postStockInLineWithQc(qcData), t, {title:"有不合格檢查項目，確認接受收貨？",
        //   confirmButtonText: t("confirm putaway"), html: ""});
        // return;
      }

      // Check if all QC items have results
      const itemsWithoutResult = qcResultsLocal.filter(item => item.qcPassed === undefined);
      
      if (itemsWithoutResult.length > 0  && stockInLineInfo?.status != StockInStatus.ESCALATED) {  //TODO: fix it please!
        validationErrors.push(`${t("QC items without result")}`);
        // validationErrors.push(`${t("QC items without result")}: ${itemsWithoutResult.map(item => item.code).join(', ')}`);
      }

      if (validationErrors.length > 0 && !skipQc) {
        console.error("QC Validation failed:", validationErrors);
        alert(`未完成品檢: ${validationErrors}`); 
        return;
      }

      const isJobOrderSource = Boolean(stockInLineInfo?.jobOrderId) || printSource === "productionProcess";
      const qcData = {
        dnNo : data.dnNo? data.dnNo : "DN00000",
        // dnDate : data.dnDate? arrayToDateString(data.dnDate, "input") : dayjsToInputDateString(dayjs()),
        productionDate : data.productionDate ? (Array.isArray(data.productionDate) ? arrayToDateString(data.productionDate, "input") : data.productionDate) : undefined,
        expiryDate : data.expiryDate ? (Array.isArray(data.expiryDate) ? arrayToDateString(data.expiryDate, "input") : data.expiryDate) : undefined,
        receiptDate : data.receiptDate ? (Array.isArray(data.receiptDate) ? arrayToDateString(data.receiptDate, "input") : data.receiptDate) : undefined,
        
        qcAccept: qcAcceptLocal ? qcAcceptLocal : false,
        acceptQty: acceptQtyLocal ? acceptQtyLocal : 0,
        // For Job Order QC, allow updating received qty beyond demand/accepted.
        // Backend uses request.acceptedQty in QC flow, so we must send it explicitly.
        acceptedQty: (qcAcceptLocal && isJobOrderSource) ? (acceptQtyLocal ? acceptQtyLocal : 0) : stockInLineInfo?.acceptedQty,
        // qcResult: itemDetail.status != "escalated" ? qcResults.map(item => ({
        qcResult: qcResultsLocal.map(item => ({
          // id: item.id,
          qcItemId: item.qcItemId,
          // code: item.code,
          // qcDescription: item.qcDescription,
          qcPassed: item.qcPassed? item.qcPassed : false,
          failQty: (item.failQty && !item.qcPassed) ? item.failQty : 0,
          // failedQty: (typeof item.failedQty === "number" && !item.isPassed) ? item.failedQty : 0,
          remarks: item.remarks || '',
        })),
      };
      // const qcData = data;

      console.log("QC Data for submission:", qcData);

      let qcRes: StockInLine | undefined;
      
      if (data.qcDecision == 3) { // Escalate
        if (data.escalationLog?.handlerId == undefined) { alert("請選擇上報負責同事！"); return; }
        else if (data.escalationLog?.handlerId < 1) { alert("上報負責同事資料有誤"); return; }
        
        const escalationLog = {
          type : "qc",
          status : "pending", // TODO: update with supervisor decision
          reason : data.escalationLog?.reason,
          recordDate : dayjsToDateTimeString(dayjs()),
          handlerId : data.escalationLog?.handlerId,
        }
        console.log("Escalation Data for submission", escalationLog);

        setIsSubmitting(true);
        const resEscalate = await postStockInLine({...qcData, escalationLog});
        qcRes = Array.isArray(resEscalate.entity) ? resEscalate.entity[0] : (resEscalate.entity as StockInLine);

      } else {
        setIsSubmitting(true);
        const resNormal = await postStockInLine(qcData);
        qcRes = Array.isArray(resNormal.entity) ? resNormal.entity[0] : (resNormal.entity as StockInLine);
      }

      if (qcData.qcAccept) {
        // submitDialogWithWarning(onOpenPutaway, t, {title:"Save success, confirm to proceed?",
        //   confirmButtonText: t("confirm putaway"), html: ""});
        // onOpenPutaway();
        const isJobOrderSource = (stockInLineInfo?.jobOrderId != null || printSource === "productionProcess");
        const isWipBom = isJobOrderSource && stockInLineInfo?.bomDescription === "WIP";
        const isFgBom  = isJobOrderSource && stockInLineInfo?.bomDescription === "FG";
        const isFaItem = (stockInLineInfo?.itemNo ?? "").toUpperCase().includes("FA");
        const shouldAutoPutaway =   isWipBom || isFgBom || isFaItem;
        if (shouldAutoPutaway) {
          // Auto putaway to default warehouse
          const loc = (itemLocationCode ?? "").trim().toUpperCase();
          const warehouseListForLookup =
            isFgBom && ((warehouse?.length ?? 0) === 0)
              ? await fetchWarehouseListClient()
              : (warehouse ?? []);
          const matchedWarehouse =
            isFgBom && loc.length > 0
              ? warehouseListForLookup.find((w) => (w.code ?? "").trim().toUpperCase().endsWith(loc))
              : undefined;
          const resolvedWarehouseId =
            (isFgBom ? matchedWarehouse?.id : undefined)
            ?? stockInLineInfo?.defaultWarehouseId
            ?? 1141;

          console.log("[AUTO_PUTAWAY_DEBUG]", {
            silId: stockInLineInfo?.id,
            bomDescription: stockInLineInfo?.bomDescription,
            isJobOrderSource,
            isWipBom,
            isFgBom,
            isFaItem,
            itemLocationCode,
            loc,
            warehouseCount: warehouse?.length,
            matchedWarehouse: matchedWarehouse ? { id: matchedWarehouse.id, code: matchedWarehouse.code } : null,
            defaultWarehouseId: stockInLineInfo?.defaultWarehouseId,
            resolvedWarehouseId,
          });
          // Get warehouse name from warehouse prop or use default
       
          
          // Create putaway data
          const putawayData = {
            id: stockInLineInfo?.id,                              // Include ID
            itemId: stockInLineInfo?.itemId,                      // Include Item ID
            purchaseOrderId: stockInLineInfo?.purchaseOrderId,    // Include PO ID if exists
            purchaseOrderLineId: stockInLineInfo?.purchaseOrderLineId, // Include POL ID if exists
            acceptedQty: acceptQtyLocal,             // Keep in sync with QC acceptQty
            acceptQty: acceptQtyLocal,               // Putaway quantity
            warehouseId: resolvedWarehouseId,
            status: "received",                                   // Use string like PutAwayModal
            productionDate: data.productionDate ? (Array.isArray(data.productionDate) ? arrayToDateString(data.productionDate, "input") : data.productionDate) : undefined,
            expiryDate: data.expiryDate ? (Array.isArray(data.expiryDate) ? arrayToDateString(data.expiryDate, "input") : data.expiryDate) : undefined,
            receiptDate: data.receiptDate ? (Array.isArray(data.receiptDate) ? arrayToDateString(data.receiptDate, "input") : data.receiptDate) : undefined,
            inventoryLotLines: [{
              warehouseId: resolvedWarehouseId,
              qty: acceptQtyLocal,                                     // Putaway qty
            }],
          } as StockInLineEntry & ModalFormInput;
          console.log("[AUTO_PUTAWAY]", {
            isFgBom,
            itemLocationCode,
            loc,
            warehouseCount: warehouse?.length,
            matchedWarehouse: isFgBom ? warehouse?.find(w => (w.code ?? "").trim().toUpperCase().endsWith(loc)) : null,
            resolvedWarehouseId,
          });
          try {
            // Use updateStockInLine directly like PutAwayModal does
            const res = await updateStockInLine(putawayData);
            if (Boolean(res.id)) {
              console.log("Auto putaway completed for job order bom");
            }
          } catch (error) {
            console.error("Error during auto putaway:", error);
            alert(t("Auto putaway failed. Please complete putaway manually."));
          }

        }
        
        closeWithResult(qcRes);
        // setTabIndex(1);  // Need to go Putaway tab?
      } else {
        closeWithResult(qcRes);
      }
      setIsSubmitting(false);      
      msg("已更新來貨狀態", {
        position:
          typeof window !== "undefined" &&
          window.location.pathname.startsWith("/po/edit")
            ? "top-end"
            : "bottom-end",
      });
      return ;

    },
    [
      stockInLineInfo,
      printSource,
      skipQc,
      warehouse,
      itemLocationCode,
      closeWithResult,
      t,
    ],
  );

  const postStockInLine = useCallback(async (args: ModalFormInput) => {
    const submitData = {
      ...stockInLineInfo, ...args
    } as StockInLineEntry & ModalFormInput;
    console.log("Submitting", submitData);

    const res = await updateStockInLine(submitData);
    return res;
  }, [stockInLineInfo])

  // Put away model
  const [pafRowModesModel, setPafRowModesModel] = useState<GridRowModesModel>({})
  const [pafRowSelectionModel, setPafRowSelectionModel] = useState<GridRowSelectionModel>([])

  const pafSubmitDisable = useMemo(() => {
    return Object.entries(pafRowModesModel).length > 0 || Object.entries(pafRowModesModel).some(([key, value], index) => value.mode === GridRowModes.Edit)
  }, [pafRowModesModel])
  // Putaway submission handler
  const onSubmitPutaway = useCallback<SubmitHandler<ModalFormInput>>(
    async (data, event) => {
      // Extract only putaway related fields
      const putawayData = {
        acceptQty: Number(data.acceptQty?? (stockInLineInfo?.demandQty?? (stockInLineInfo?.acceptedQty))),  //TODO improve
        warehouseId: data.warehouseId,
        status: data.status, //TODO Fix it!
        // ...data,
        
        // dnDate : data.dnDate? arrayToDateString(data.dnDate, "input") : dayjsToInputDateString(dayjs()),
        productionDate : arrayToDateString(data.productionDate, "input"),
        expiryDate : arrayToDateString(data.expiryDate, "input"),
        receiptDate : arrayToDateString(data.receiptDate, "input"),

        // for putaway data
        inventoryLotLines: data.putAwayLines?.filter((line) => line._isNew !== false)

        // Add other putaway specific fields
      } as ModalFormInput;
      console.log("Putaway Data:", putawayData);

      console.log("DEBUG",data.putAwayLines);
      // if (data.putAwayLines!!.filter((line) => line._isNew !== false).length <= 0) { 
      //   alert("請新增上架資料！");
      //   return;
      //  }
      if (data.putAwayLines!!.filter((line) => /[^0-9]/.test(String(line.qty))).length > 0) {  //TODO Improve
        alert("上架數量不正確！");
        return;
      }
      if (data.putAwayLines!!.reduce((acc, cur) => acc + Number(cur.qty), 0) > putawayData.acceptQty!!) {
        alert(`上架數量不能大於 ${putawayData.acceptQty}！`);
        return;
      }
      // Handle putaway submission logic here
      const res = await postStockInLine(putawayData);
      console.log("result ", res);
      
      // Close modal after successful putaway
      closeHandler({}, "backdropClick");
    },
    [closeHandler],
  );
  // Print handler
  useEffect(() => {
    if (!printerCombo.length) return;
    if (typeof window === "undefined") {
      setSelectedPrinter(printerCombo[0]);
      return;
    }

    const savedId = sessionStorage.getItem(printerStorageKey);
    const matched = savedId ? printerCombo.find(p => p.id === Number(savedId)) : undefined;
    setSelectedPrinter(matched ?? printerCombo[0]);
  }, [printerCombo, printerStorageKey]);
  const [isPrinting, setIsPrinting] = useState(false)
  const handlePrint = useCallback(async () => {
    // console.log("Print putaway documents");
    console.log("%c data", "background: white; color: red", formProps.watch("putAwayLines"));
    // Handle print logic here
    // window.print();
    // const postData = { stockInLineIds: [itemDetail.id]};
    // const response = await fetchPoQrcode(postData);
    // if (response) {
    //   downloadFile(new Uint8Array(response.blobValue), response.filename)
    // }
    try {
      setIsPrinting(() => true)
      if ((formProps.watch("putAwayLines") ?? []).filter((line) => /[^0-9]/.test(String(line.printQty))).length > 0) {  //TODO Improve
        alert("列印數量不正確！");
        return;
      }
    // Conditionally call different APIs based on source
    let response;
    if (printSource === "productionProcess") {
      // Use FG Stock In Label print API for production process
      const data: PrintFGStockInLabelRequest = {
        stockInLineId: stockInLineInfo?.id ?? 0,
        printerId: selectedPrinter.id,
        printQty: printQty
      }
      response = await printFGStockInLabel(data);
    } else {
      // Use stock-in print API (default)
      const data: PrintQrCodeForSilRequest = {
        stockInLineId: stockInLineInfo?.id ?? 0,
        printerId: selectedPrinter.id,
        printQty: printQty
      }
      response = await printQrCodeForSil(data);
    }
    
    if (response) {
      console.log(response)
    }
    if (typeof window !== 'undefined' && selectedPrinter) {
      sessionStorage.setItem(printerStorageKey, String(selectedPrinter.id));
    }
  } finally {
    setIsPrinting(() => false)
  }
}, [stockInLineInfo?.id, pafRowSelectionModel, printQty, selectedPrinter, printSource]);
  
  // const checkQcIsPassed = useCallback((qcItems: PurchaseQcResult[]) => {
  //   const isPassed = qcItems.every((qc) => qc.qcPassed);
  //   console.log(isPassed)
  //   if (isPassed) {
  //       formProps.setValue("passingQty", acceptQty)
  //   } else {
  //       formProps.setValue("passingQty", 0)
  //   }
  //   return isPassed
  // }, [acceptQty, formProps])

const printQrcode = useCallback(
  async () => {
    setIsPrinting(true);
    try {
      let response;
      
    if (printSource === "productionProcess") {
      // Use FG Stock In Label download API for production process
      if (!stockInLineInfo?.id) {
        console.error("Stock In Line ID is required for download");
        setIsPrinting(false);
        return;
      }
      const postData = { stockInLineId: stockInLineInfo.id };
      response = await fetchFGStockInLabel(postData);
    } else {
      const postData = { stockInLineIds: [stockInLineInfo?.id] };
      response = await fetchPoQrcode(postData);
    }
      
      if (response) {
        console.log(response);
        downloadFile(new Uint8Array(response.blobValue), response.filename!);
      }
    } catch (e) {
      console.log("%c Error downloading QR Code", "color:red", e);
    } finally {
      setIsPrinting(false);
    }
  },
  [stockInLineInfo, printSource],
);

  return (
    <>
      <FormProvider {...formProps}>
        <Modal open={open} onClose={closeHandler}>
          <Box
            sx={{
              ...style,
              // padding: 2,
              maxHeight: "90vh",
              overflowY: "auto",
              marginLeft: 3,
              marginRight: 3,
              // overflow: "hidden",
              display: 'flex',
              flexDirection: 'column',
            }}
          >
          {(!isLoading && stockInLineInfo) ? (<>
            <Box sx={{ position: 'sticky', top: 0, bgcolor: 'background.paper',
              zIndex: 5, borderBottom: 2, borderColor: 'divider', width: "100%"}}>
              <Tabs
                value={tabIndex}
                onChange={handleTabChange}
                variant="scrollable"
                sx={{pl: 2, pr: 2, pt: 2}}
              >
                <Tab label={
                  showPutaway ? t("dn and qc info") : t("qc processing")
                } iconPosition="end" />
                {showPutaway && <Tab label={t("putaway processing")} iconPosition="end" />}
              </Tabs>
            </Box>
            <Grid
              container
              justifyContent="flex-start"
              alignItems="flex-start"
              sx={{padding: 2}}
            >
              <Grid item xs={12}>
              {tabIndex === 0 && 
                <Box>
                  <Grid item xs={12}>
                    <Typography variant="subtitle1" display="block" marginBlockEnd={1} fontWeight={600}>
                      {t("Delivery Detail")}
                    </Typography>
                  </Grid>
                  {stockInLineInfo.jobOrderId ? (
                    <FgStockInForm
                      itemDetail={stockInLineInfo}
                      disabled={viewOnly || showPutaway}
                      compactFields={useCompactFields}
                    />
                  ) : (
                    <StockInForm
                      itemDetail={stockInLineInfo}
                      disabled={viewOnly || showPutaway}
                      compactFields={useCompactFields}
                    />
                  )}
                  {skipQc === false && (
                    <QcComponent
                    itemDetail={stockInLineInfo}
                    disabled={viewOnly || showPutaway}
                    compactLayout={uiMode === "dashboard" || uiMode === "productionProcess"}
                    denseLayout={useDenseQcLayout}
                  />)
                  }
                  <Stack direction="row" justifyContent="flex-end" gap={1} sx={{pt:2}}>
                    {(!viewOnly && !showPutaway) && (<Button
                      id="Submit"
                      type="button"
                      variant="contained"
                      color="primary"
                      sx={{ mt: 1 }}
                      onClick={formProps.handleSubmit(onSubmitQc, onSubmitErrorQc)}
                      disabled={isSubmitting || isLoading}
                    >
                      {isSubmitting ? (t("submitting")) : (skipQc ? t("confirm") : t("confirm qc result"))}
                    </Button>)}
                  </Stack>
                </Box>
              }

              {tabIndex === 1 &&
                <Box>


                  <PutAwayForm
                    itemDetail={stockInLineInfo}
                    warehouse={warehouse!}
                    disabled={viewOnly}
                    setRowModesModel={setPafRowModesModel}
                    setRowSelectionModel={setPafRowSelectionModel}
                    suggestedLocationCode={itemLocationCode || undefined}
                  />
                </Box>
                }
              </Grid>
            </Grid>
            
            {tabIndex == 1 && (
              <Stack direction="row" justifyContent="flex-end" gap={1} sx={{m:3, mt:"auto"}}>
                <Autocomplete
                disableClearable
                options={labelPrinterCombo}
                getOptionLabel={(option) =>
                  option.name || option.label || option.code || `Printer ${option.id}`
                }
                value={selectedPrinter}
                onChange={(_, newValue) => {
                  if (newValue) setSelectedPrinter(newValue);
                }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    variant="outlined"
                    label={t("Printer")}
                    sx={{ width: 300 }}
                    inputProps={{ ...params.inputProps, readOnly: true }}
                  />
                )}
              />
                <TextField
                  variant="outlined"
                  label={t("Print Qty")}
                  defaultValue={printQty}
                  onChange={(event) => {
                    event.target.value = event.target.value.replace(/[^0-9]/g, '')

                    setPrintQty(Number(event.target.value))
                  }}
                  sx={{ width: 300}}
                />
                <Button
                  id="printButton"
                  type="button"
                  variant="contained"
                  color="primary"
                  sx={{ mt: 1 }}
                  onClick={handlePrint}
                  disabled={isPrinting || printerCombo.length <= 0 || pafSubmitDisable}
                >
                  {isPrinting ? t("Printing") : t("print")}
                </Button>
                <Button
                  id="demoPrint"
                  type="button"
                  variant="contained"
                  color="primary"
                  sx={{ mt: 1 }}
                  onClick={printQrcode}
                  disabled={isPrinting}
                >
                  {isPrinting ? t("downloading") : t("download Qr Code")}
                </Button>
              </Stack>
            )}
          </>) : <LoadingComponent/>}
          </Box>
        </Modal>
      </FormProvider>
    </>
  );
};
export default QcStockInModal;
