"use client";
import {
  FooterPropsOverrides,
  GridActionsCellItem,
  GridCellParams,
  GridRowId,
  GridRowIdGetter,
  GridRowModel,
  GridRowModes,
  GridRowModesModel,
  GridToolbarContainer,
  GridValidRowModel,
  useGridApiRef,
} from "@mui/x-data-grid";
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import StyledDataGrid from "../StyledDataGrid";
import { GridColDef } from "@mui/x-data-grid";
import { Box, Button, Grid, Typography } from "@mui/material";
import { useTranslation } from "react-i18next";
import { Add } from "@mui/icons-material";
import SaveIcon from "@mui/icons-material/Save";
import DeleteIcon from "@mui/icons-material/Delete";
import CancelIcon from "@mui/icons-material/Cancel";
import FactCheckIcon from "@mui/icons-material/FactCheck";
import ShoppingCartIcon from "@mui/icons-material/ShoppingCart";
// import { QcItemWithChecks } from "src/app/api/qc";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import { PurchaseOrderLine } from "@/app/api/po";
import { StockInLine } from "@/app/api/stockIn";
import { createStockInLine, PurchaseQcResult } from "@/app/api/stockIn/actions";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  returnWeightUnit,
  calculateWeight,
  stockInLineStatusMap,
  arrayToDateString,
} from "@/app/utils/formatUtil";
// import PoQcStockInModal from "./PoQcStockInModal";
import NotificationImportantIcon from "@mui/icons-material/NotificationImportant";
import { WarehouseResult } from "@/app/api/warehouse";
import LooksOneIcon from "@mui/icons-material/LooksOne";
import LooksTwoIcon from "@mui/icons-material/LooksTwo";
import Looks3Icon from "@mui/icons-material/Looks3";
import axiosInstance from "@/app/(main)/axios/axiosInstance";
// import axios, { AxiosRequestConfig } from "axios";
import { BASE_API_URL, NEXT_PUBLIC_API_URL } from "@/config/api";
import qs from "qs";
import QrCodeIcon from "@mui/icons-material/QrCode";
import { downloadFile } from "@/app/utils/commonUtil";
import { fetchPoQrcode } from "@/app/api/pdf/actions";
import { fetchQcResult } from "@/app/api/qc/actions";
import PoQcStockInModal from "./PoQcStockInModal";
import DoDisturbIcon from "@mui/icons-material/DoDisturb";
import { useSession } from "next-auth/react";
// import { SessionWithTokens } from "src/config/authConfig";
import QcStockInModal from "./QcStockInModal";
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
import { PrinterCombo } from "@/app/api/settings/printer";
import { EscalationResult } from "@/app/api/escalation";
import { fetchEscalationLogsByStockInLines } from "@/app/api/escalation/actions";
import { SessionWithTokens } from "@/config/authConfig";
import { EscalationCombo } from "@/app/api/user";

interface ResultWithId {
  id: number;
}

interface Props {
  // qc: QcItemWithChecks[];
  setRows: Dispatch<SetStateAction<PurchaseOrderLine[]>>;
  setStockInLine: Dispatch<SetStateAction<StockInLine[]>>;
  setProcessedQty: Dispatch<SetStateAction<number>>;
  itemDetail: PurchaseOrderLine;
  stockInLine: StockInLine[];
  warehouse: WarehouseResult[];
  fetchPoDetail: (poId: string) => void;
  handleMailTemplateForStockInLine: (stockInLineId: number) => void;
  printerCombo: PrinterCombo[];
}

export type StockInLineEntryError = {
  [field in keyof StockInLine]?: string;
};

export type StockInLineRow = Partial<
  StockInLine & {
    isActive: boolean | undefined;
    _isNew: boolean;
    _error: StockInLineEntryError;
  } & ResultWithId
>;

class ProcessRowUpdateError extends Error {
  public readonly row: StockInLineRow;
  public readonly errors: StockInLineEntryError | undefined;
  constructor(
    row: StockInLineRow,
    message?: string,
    errors?: StockInLineEntryError,
  ) {
    super(message);
    this.row = row;
    this.errors = errors;

    Object.setPrototypeOf(this, ProcessRowUpdateError.prototype);
  }
}

function PoInputGrid({
  // qc,
  setRows,
  setStockInLine,
  setProcessedQty,
  itemDetail,
  stockInLine,
  warehouse,
  fetchPoDetail,
  handleMailTemplateForStockInLine,
  printerCombo,
}: Props) {

  const { t } = useTranslation("purchaseOrder");
  const apiRef = useGridApiRef();
  const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
  const getRowId = useCallback<GridRowIdGetter<StockInLineRow>>(
    (row) => row.id as number,
    [],
  );

  const [entries, setEntries] = useState<StockInLineRow[]>(stockInLine || []);
  useEffect(() => {
    setEntries(stockInLine);
  }, [stockInLine])
  const [modalInfo, setModalInfo] = useState<
    StockInLine & { qcResult?: PurchaseQcResult[] } & { escalationResult?: EscalationResult[] }
  >();
  const pathname = usePathname()
  const router = useRouter();
  const searchParams = useSearchParams();

  const [qcOpen, setQcOpen] = useState(false);
  const [escalOpen, setEscalOpen] = useState(false);
  const [stockInOpen, setStockInOpen] = useState(false);
  const [putAwayOpen, setPutAwayOpen] = useState(false);
  const [rejectOpen, setRejectOpen] = useState(false);
  const [btnIsLoading, setBtnIsLoading] = useState(false);
  const [currQty, setCurrQty] = useState(() => {
    const total = entries.reduce(
      (acc, curr) => acc + (curr.acceptedQty || 0),
      0,
    );
    return total;
  });

  const { data: session } = useSession();
  const sessionToken = session as SessionWithTokens | null;

  useEffect(() => {
    const completedList = entries.filter(
      (e) => stockInLineStatusMap[e.status!] >= 8,
    );
    const processedQty = completedList.reduce(
      (acc, curr) => acc + (curr.acceptedQty || 0),
      0,
    );
    setProcessedQty(processedQty);
  }, [entries, setProcessedQty]);

  const handleDelete = useCallback(
    (id: GridRowId) => () => {
      setEntries((es) => es.filter((e) => getRowId(e) !== id));
    },
    [getRowId],
  );
  
  const closeQcModal = useCallback(() => {
    setQcOpen(false);
  }, []);
  const openQcModal = useCallback(() => {
    setQcOpen(true);
  }, []);

  const closeStockInModal = useCallback(() => {
    setStockInOpen(false);
  }, []);
  const openStockInModal = useCallback(() => {
    setStockInOpen(true);
  }, []);

  const closePutAwayModal = useCallback(() => {
    setPutAwayOpen(false);
  }, []);
  const openPutAwayModal = useCallback(() => {
    setPutAwayOpen(true);
  }, []);

  const closeEscalationModal = useCallback(() => {
    setEscalOpen(false);
  }, []);
  const openEscalationModal = useCallback(() => {
    setEscalOpen(true);
  }, []);

  const closeRejectModal = useCallback(() => {
    setRejectOpen(false);
  }, []);
  const openRejectModal = useCallback(() => {
    setRejectOpen(true);
  }, []);

  const handleStart = useCallback(  // NOTE: Seems unused!!!!!!!!
    (id: GridRowId, params: any) => () => {
      setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      setTimeout(async () => {
        // post stock in line
        const oldId = params.row.id;
        const postData = {
          itemId: params.row.itemId,
          itemNo: params.row.itemNo,
          itemName: params.row.itemName,
          // purchaseOrderId: params.row.purchaseOrderId,
          purchaseOrderLineId: params.row.purchaseOrderLineId,
          acceptedQty: params.row.acceptedQty,
        };
        const res = await createStockInLine(postData);
        console.log(res);
        setEntries((prev) =>
          prev.map((p) => (p.id === oldId ? (res.entity as StockInLine) : p)),
        );
        setStockInLine(
          (prev) =>
            prev.map((p) =>
              p.id === oldId ? (res.entity as StockInLine) : p,
            ) as StockInLine[],
        );
        setBtnIsLoading(false);
        // do post directly to test
        // openStartModal();
      }, 200);
    },
    [setStockInLine],
  );
  const fetchQcDefaultValue = useCallback(async (stockInLineId: GridRowId) => {
    return await fetchQcResult(stockInLineId as number);
  }, []);

  const handleQC = useCallback( // UNUSED NOW!
    (id: GridRowId, params: any) => async () => {
      setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      const qcResult = await fetchQcDefaultValue(id);
      // console.log(params.row);
      console.log("Fetched QC Result:", qcResult);
      
      setModalInfo({
        ...params.row,
        qcResult: qcResult,
      });
      // set default values
      setTimeout(() => {
        // open qc modal
        console.log("delayed");
        openQcModal();
        setBtnIsLoading(false);
      }, 200);
    },
    [fetchQcDefaultValue, openQcModal],
  );

  const [newOpen, setNewOpen] = useState(false);
  const stockInLineId = searchParams.get("stockInLineId");
  const poLineId = searchParams.get("poLineId");

const closeNewModal = useCallback(() => {
  const newParams = new URLSearchParams(searchParams.toString());
  newParams.delete("stockInLineId"); // Remove the parameter
  router.replace(`${pathname}?${newParams.toString()}`);
  fetchPoDetail(itemDetail.purchaseOrderId.toString());
  setNewOpen(false); // Close the modal first
  // setTimeout(() => {
  //   }, 300); // Add a delay to avoid immediate re-trigger of useEffect
  }, [searchParams, pathname, router]);

  // Open modal
  const openNewModal = useCallback(() => {
    setNewOpen(() => true);
  }, []);

  // Button handler to update the URL and open the modal
  const handleNewQC = useCallback(
    (id: GridRowId, params: any) => async() => {
      // setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      
      // const qcResult = await fetchQcDefaultValue(id);
      // const escResult = await fetchEscalationLogsByStockInLines([Number(id)]);
      setModalInfo(() => ({
        ...params.row,
        // qcResult: qcResult,
        // escResult: escResult,
        receivedQty: itemDetail.receivedQty,
      }));
      
      const newParams = new URLSearchParams(searchParams.toString());
      newParams.set("stockInLineId", id.toString()); // Ensure `set` to avoid duplicates
      router.replace(`${pathname}?${newParams.toString()}`);
      openNewModal()
      // setTimeout(() => {
      // }, 200);
    },
    [fetchQcDefaultValue, openNewModal, pathname, router, searchParams]
  );

  // Open modal if `stockInLineId` exists in the URL
  const [firstCheckForSil, setFirstCheckForSil] = useState(false)
  useEffect(() => {
    if (stockInLineId && itemDetail && !firstCheckForSil) {
      // console.log(stockInLineId)
      // console.log(apiRef.current.getRow(stockInLineId))
      setFirstCheckForSil(true)
      const fn = handleNewQC(stockInLineId, {row: apiRef.current.getRow(stockInLineId)});
      fn();
    }
  }, [stockInLineId, poLineId, itemDetail]);
  const handleEscalation = useCallback(
    (id: GridRowId, params: any) => () => {
      // setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      setModalInfo(params.row);
      setTimeout(() => {
        // open qc modal
        console.log("delayed");
        openEscalationModal();
        // setBtnIsLoading(false);
      }, 200);
    },
    [openEscalationModal],
  );

  const handleReject = useCallback(
    (id: GridRowId, params: any) => () => {
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      setModalInfo(params.row);
      setTimeout(() => {
        // open stock in modal
        // openPutAwayModal();
        // return the record with its status as pending
        // update layout
        console.log("delayed");
        openRejectModal();
        // printQrcode(params.row);
      }, 200);
    },
    [openRejectModal],
  );

  const handleStockIn = useCallback(
    (id: GridRowId, params: any) => () => {
      // setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      setModalInfo(params.row);
      setTimeout(() => {
        // open stock in modal
        openStockInModal();
        // return the record with its status as pending
        // update layout
        console.log("delayed");
        // setBtnIsLoading(false);
      }, 200);
    },
    [openStockInModal],
  );

  const handlePutAway = useCallback(
    (id: GridRowId, params: any) => () => {
      // setBtnIsLoading(true);
      setRowModesModel((prev) => ({
        ...prev,
        [id]: { mode: GridRowModes.View },
      }));
      setModalInfo(params.row);
      setTimeout(() => {
        // open stock in modal
        openPutAwayModal();
        // return the record with its status as pending
        // update layout
        console.log("delayed");
        // setBtnIsLoading(false);
      }, 200);
    },
    [openPutAwayModal],
  );

  const printQrcode = useCallback(
    async (row: any) => {
      setBtnIsLoading(true);
      console.log(row.id);
      const postData = { stockInLineIds: [row.id] };
      // const postData = { stockInLineIds: [42,43,44] };
      const response = await fetchPoQrcode(postData);
      if (response) {
        console.log(response);
        downloadFile(new Uint8Array(response.blobValue), response.filename!);
      }
      setBtnIsLoading(false);
    },
    [],
  );

  const getButtonSx = (sil : StockInLine) => {
    const status = sil?.status?.toLowerCase();
    let btnSx = {label:"", color:""};
    switch (status) {
      case "received": btnSx = {label: t("view putaway"), color:"secondary.main"}; break;
      case "escalated": if (sessionToken?.id == sil?.handlerId) { 
        btnSx = {label: t("escalation processing"), color:"warning.main"};
        break;}
      case "rejected": 
      case "partially_completed":
      case "completed": btnSx = {label: t("view stockin"), color:"info.main"}; break;
      default: btnSx = {label: t("qc processing"), color:"success.main"};
    }
    return btnSx
  };

  // const handleQrCode = useCallback(
  //   (id: GridRowId, params: any) => () => {
  //     setRowModesModel((prev) => ({
  //       ...prev,
  //       [id]: { mode: GridRowModes.View },
  //     }));
  //     setModalInfo(params.row);
  //     setTimeout(() => {
  //       // open stock in modal
  //       // openPutAwayModal();
  //       // return the record with its status as pending
  //       // update layout
  //       console.log("delayed");
  //       printQrcode(params.row);
  //     }, 200);
  //   },
  //   [printQrcode],
  // );

  const columns = useMemo<GridColDef[]>(
    () => [
      // {
      //   field: "itemNo",
      //   headerName: t("itemNo"),
      //   width: 100,
      //   // flex: 0.4,
      // },
      {
        field: "dnNo",
        headerName: t("dnNo"),
        width: 125,
        // renderCell: () => {
        //   return <>DN0000001</>
        // }
        // flex: 0.4,
      },
      {
        field: "receiptDate",
        headerName: t("receiptDate"),
        width: 125,
        renderCell: (params) => {
          // console.log(params.row)
          // return <>07/08/2025</>
          return arrayToDateString(params.value)
        }
        // flex: 0.4,
      },
      {
        field: "productLotNo",
        headerName: t("productLotNo"),
        width: 125,
      },
      // {
      //   field: "itemName",
      //   headerName: t("itemName"),
      //   width: 100,
      //   // flex: 0.6,
      // },
      {
        field: "acceptedQty",
        headerName: t("acceptedQty"),
        // flex: 0.5,
        width: 125,
        type: "number",
        // editable: true,
        // replace with tooltip + content
        renderCell: (params) => {
          return integerFormatter.format(params.value)
        }
      },
      {
        field: "uom",
        headerName: t("uom"),
        width: 150,
        // flex: 0.5,
        renderCell: (params) => {
          return params.row.uom?.udfudesc;
        },
      },
      {
        field: "stockQty",
        headerName: t("Stock In Qty"),
        // flex: 0.5,
        width: 125,
        type: "number",
        // editable: true,
        // replace with tooltip + content
        renderCell: (params) => {
          const baseQty = (params.row.acceptedQty ?? 0) * (itemDetail.stockUom.purchaseRatioN ?? 1) / (itemDetail.stockUom.purchaseRatioD ?? 1)
          const stockQty = baseQty * (itemDetail.stockUom.stockRatioD ?? 1) / (itemDetail.stockUom.stockRatioN ?? 1)
          return decimalFormatter.format(stockQty)
        }
      },
      {
        field: "stockUom",
        headerName: t("Stock UoM"),
        width: 150,
        // flex: 0.5,
        renderCell: (params) => {
          return itemDetail.stockUom.stockUomDesc;
        },
      },
      // {
      //   field: "weight",
      //   headerName: t("weight"),
      //   width: 120,
      //   // flex: 0.5,
      //   renderCell: (params) => {
      //     const weight = calculateWeight(
      //       params.row.acceptedQty,
      //       params.row.uom,
      //     );
      //     const weightUnit = returnWeightUnit(params.row.uom);
      //     return `${decimalFormatter.format(weight)} ${weightUnit}`;
      //   },
      // },
      {
        field: "status",
        headerName: t("Status"),
        width: 140,
        // flex: 0.5,
        renderCell: (params) => {
          const handlerId = params.row.handlerId
          const status = params.row.status
          return (<span style={{
            color:
            (status == "escalated")? "red":
              (status == "rejected" || status == "partially_completed") ? "orange" : "inherit"}}
            >
              {t(`${params.row.status}`)}
            </span>);
        },
      },
      {
        field: "actions",
        type: "actions",
        // headerName: `${t("start")} | ${t("qc")} | ${t("escalation")} | ${t(
        //   "stock in",
        // )} | ${t("putaway")} | ${t("delete")}`,
        headerName: "操作",
        // headerName: "start | qc | escalation | stock in | putaway | delete",
        width: 350, //200
        // flex: 2,
        cellClassName: "actions",
        getActions: (params) => {
          const data = params.row;
          // console.log(params.row.status);
          const btnSx = getButtonSx(data);
          // console.log(stockInLineStatusMap[status]);
          // console.log(session?.user?.abilities?.includes("APPROVAL"));
          return [
            <GridActionsCellItem
              icon={<Button variant="contained" sx={{ width: '150px', backgroundColor: btnSx.color }}>
                {btnSx.label}</Button>}
              label="start"
              sx={{
                // color: "primary.main",
                // marginRight: 1,
              }}
              onClick={handleNewQC(params.row.id, params)}
              color="inherit"
              key={`edit`}
            />,
            <GridActionsCellItem
              icon={
                data.status !== "received" ?
                (<Button
                  id="emailSupplier"
                  type="button"
                  variant="contained"
                  color="primary"
                  sx={{  width: '150px' }}
                  disabled={params.row.status != "rejected" && params.row.status != "partially_completed"}
                  onClick={() => handleMailTemplateForStockInLine(params.row.id as number)}
                >
                  {t("email supplier")}
                </Button>) : (
                  <Button
                  id="printQrCode"
                  type="button"
                  variant="contained"
                  // color="red"
                  sx={{  width: '150px', backgroundColor: '#7f434a' }}
                  disabled={btnIsLoading || data.status != "received"}
                  onClick={() => printQrcode(params.row)}
                >
                  {t("printQrCode")}
                </Button>
                )
              }
              label="start"
              sx={{
                // color: "primary.main",
                // marginRight: 1,
              }}
              // onClick={handleNewQC(params.row.id, params)}
              color="inherit"
              key="edit"
            />,
            // <GridActionsCellItem
            //   icon={<Button variant="contained">{t("putawayBtn")}</Button>}
            //   label="start"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   // disabled={!(stockInLineStatusMap[status] === 0)}
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handleStart(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,

            // <GridActionsCellItem
            //   icon={<Button variant="contained">{t("qc processing")}</Button>}
            //   label="start"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   disabled={!(stockInLineStatusMap[status] === 0)}
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handleStart(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,
            // <GridActionsCellItem
            //   icon={<FactCheckIcon />}
            //   label="qc"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   disabled={
            //     // stockInLineStatusMap[status] === 9 ||
            //     stockInLineStatusMap[status] < 1
            //   }
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handleQC(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,
            // <GridActionsCellItem
            //   icon={<NotificationImportantIcon />}
            //   label="escalation"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   disabled={
            //     stockInLineStatusMap[status] === 9 ||
            //     stockInLineStatusMap[status] <= 0 ||
            //     stockInLineStatusMap[status] >= 5
            //   }
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handleEscalation(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,
            // <GridActionsCellItem
            //   icon={<ShoppingCartIcon />}
            //   label="stockin"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   disabled={
            //     stockInLineStatusMap[status] === 9 ||
            //     stockInLineStatusMap[status] <= 2 ||
            //     stockInLineStatusMap[status] >= 7 ||
            //     (stockInLineStatusMap[status] >= 3 &&
            //       stockInLineStatusMap[status] <= 5 &&
            //       !session?.user?.abilities?.includes("APPROVAL"))
            //     }
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handleStockIn(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,
            // <GridActionsCellItem
            //   icon={<ShoppingCartIcon />}
            //   label="putaway"
            //   sx={{
            //     color: "primary.main",
            //     // marginRight: 1,
            //   }}
            //   disabled={
            //     stockInLineStatusMap[status] === 9 ||
            //     stockInLineStatusMap[status] < 7
            //   }
            //   // set _isNew to false after posting
            //   // or check status
            //   onClick={handlePutAway(params.row.id, params)}
            //   color="inherit"
            //   key="edit"
            // />,
            // // <GridActionsCellItem
            // //   icon={<QrCodeIcon />}
            // //   label="putaway"
            // //   sx={{
            // //     color: "primary.main",
            // //     // marginRight: 1,
            // //   }}
            // //   disabled={stockInLineStatusMap[status] === 9 || stockInLineStatusMap[status] !== 8}
            // //   // set _isNew to false after posting
            // //   // or check status
            // //   onClick={handleQrCode(params.row.id, params)}
            // //   color="inherit"
            // //   key="edit"
            // // />,
            // <GridActionsCellItem
            //   icon={
            //     stockInLineStatusMap[status] >= 1 ? (
            //       <DoDisturbIcon />
            //     ) : (
            //       <DeleteIcon />
            //     )
            //   }
            //   label="Delete"
            //   sx={{
            //     color: "error.main",
            //   }}
            //   disabled={
            //     stockInLineStatusMap[status] >= 7 &&
            //     stockInLineStatusMap[status] <= 9
            //   }
            //   onClick={
            //     stockInLineStatusMap[status] === 0
            //       ? handleDelete(params.row.id)
            //       : handleReject(params.row.id, params)
            //   }
            //   color="inherit"
            //   key="edit"
            // />,
          ];
        },
      },
    ],
    [t, handleStart, handleQC, handleEscalation, handleStockIn, handlePutAway, handleDelete, handleReject, itemDetail],
  );

  const unsortableColumns = useMemo(() => 
    columns.map(column => ({ ...column, sortable: false }))
  , [columns]);

  const addRow = useCallback(() => {
    console.log(itemDetail);
    const newEntry = {
      id: Date.now(),
      _isNew: true,
      itemId: itemDetail.itemId,
      purchaseOrderId: itemDetail.purchaseOrderId,
      purchaseOrderLineId: itemDetail.id,
      itemNo: itemDetail.itemNo,
      itemName: itemDetail.itemName,
      acceptedQty: itemDetail.qty - currQty, // this bug
      uom: itemDetail.uom,
      status: "draft",
    };
    setEntries((e) => [...e, newEntry]);
    setRowModesModel((model) => ({
      ...model,
      [getRowId(newEntry)]: {
        mode: GridRowModes.Edit,
        // fieldToFocus: "projectId",
      },
    }));
  }, [currQty, getRowId, itemDetail]);

  const validation = useCallback(
    (
      newRow: GridRowModel<StockInLineRow>,
      //   rowModel: GridRowSelectionModel
    ): StockInLineEntryError | undefined => {
      const error: StockInLineEntryError = {};
      console.log(newRow);
      console.log(currQty);
      if (newRow.acceptedQty && newRow.acceptedQty > itemDetail.qty) {
        error["acceptedQty"] = t("qty cannot be greater than remaining qty");
      }
      return Object.keys(error).length > 0 ? error : undefined;
    },
    [currQty, itemDetail.qty, t],
  );
  const processRowUpdate = useCallback(
    (
      newRow: GridRowModel<StockInLineRow>,
      originalRow: GridRowModel<StockInLineRow>,
    ) => {
      const errors = validation(newRow); // change to validation
      if (errors) {
        throw new ProcessRowUpdateError(
          originalRow,
          "validation error",
          errors,
        );
      }
      const { _isNew, _error, ...updatedRow } = newRow;
      const rowToSave = {
        ...updatedRow,
      } satisfies StockInLineRow;
      const newEntries = entries.map((e) =>
        getRowId(e) === getRowId(originalRow) ? rowToSave : e,
      );
      setStockInLine(newEntries as StockInLine[]);
      console.log("triggered");
      setEntries(newEntries);
      //update remaining qty
      const total = newEntries.reduce(
        (acc, curr) => acc + (curr.acceptedQty || 0),
        0,
      );
      setCurrQty(total);
      return rowToSave;
    },
    [validation, entries, setStockInLine, getRowId],
  );

  const onProcessRowUpdateError = useCallback(
    (updateError: ProcessRowUpdateError) => {
      const errors = updateError.errors;
      const oldRow = updateError.row;

      apiRef.current.updateRows([{ ...oldRow, _error: errors }]);
    },
    [apiRef],
  );

  const footer = (
    <>
      {/* <Box display="flex" gap={2} alignItems="center">
        <Button
          disableRipple
          variant="outlined"
          startIcon={<Add />}
          disabled={itemDetail.qty - currQty <= 0}
          onClick={addRow}
          size="small"
        >
          {t("Record pol")}
        </Button>
      </Box> */}
    </>
  );
  
  return (
    <>
      <StyledDataGrid
        getRowId={getRowId}
        apiRef={apiRef}
        autoHeight
        sx={{
          "--DataGrid-overlayHeight": "100px",
          ".MuiDataGrid-row .MuiDataGrid-cell.hasError": {
            border: "1px solid",
            borderColor: "error.main",
          },
          ".MuiDataGrid-row .MuiDataGrid-cell.hasWarning": {
            border: "1px solid",
            borderColor: "warning.main",
          },
        }}
        disableColumnMenu
        editMode="row"
        rows={entries}
        rowModesModel={rowModesModel}
        onRowModesModelChange={setRowModesModel}
        processRowUpdate={processRowUpdate}
        onProcessRowUpdateError={onProcessRowUpdateError}
        columns={unsortableColumns}
        isCellEditable={(params) => {
          const status = params.row.status.toLowerCase();
          return (
            stockInLineStatusMap[status] >= 0 ||
            stockInLineStatusMap[status] <= 1
          );
        }}
        getCellClassName={(params: GridCellParams<StockInLineRow>) => {
          let classname = "";
          if (params.row._error) {
            classname = "hasError";
          }
          return classname;
        }}
        slots={{
          footer: FooterToolbar,
          noRowsOverlay: NoRowsOverlay,
        }}
        slotProps={{
          footer: { child: footer },
        }}
      />
      {/* {modalInfo !== undefined && ( */}
        <>
          <QcStockInModal
            session={sessionToken}
            open={newOpen}
            onClose={closeNewModal}
            // itemDetail={modalInfo}
            inputDetail={modalInfo}
            printerCombo={printerCombo}
          />
        </>
        {/* )
      } */}
    </>
  );
}
const NoRowsOverlay: React.FC = () => {
  const { t } = useTranslation("home");
  return (
    <Box
      display="flex"
      justifyContent="center"
      alignItems="center"
      height="100%"
    >
      <Typography variant="caption">{t("Add some entries!")}</Typography>
    </Box>
  );
};

const FooterToolbar: React.FC<FooterPropsOverrides> = ({ child }) => {
  return <GridToolbarContainer sx={{ p: 2 }}>{child}</GridToolbarContainer>;
};
export default PoInputGrid;
