"use client";

import {
  fetchPoWithStockInLines,
  PoResult,
  PurchaseOrderLine,
  StockInLine,
} from "@/app/api/po";
import {
  Box,
  Button,
  ButtonProps,
  Collapse,
  Grid,
  IconButton,
  Paper,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  TabsProps,
  TextField,
  Typography,
  Checkbox,
  FormControlLabel,
  Card,
  CardContent,
  Radio,
} from "@mui/material";
import { useTranslation } from "react-i18next";
// import InputDataGrid, { TableRow } from "../InputDataGrid/InputDataGrid";
import {
  GridColDef,
  GridRowId,
  GridRowModel,
  useGridApiRef,
} from "@mui/x-data-grid";
import {
  checkPolAndCompletePo,
  fetchPoInClient,
  fetchPoListClient,
  fetchStockInLineInfo,
  PurchaseQcResult,
  startPo,
  createStockInLine
} from "@/app/api/po/actions";
import {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import PoInputGrid from "./PoInputGrid";
import { QcItemWithChecks } from "@/app/api/qc";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { WarehouseResult } from "@/app/api/warehouse";
import { calculateWeight, dateStringToDayjs, dayjsToDateString, OUTPUT_DATE_FORMAT, outputDateStringToInputDateString, returnWeightUnit } from "@/app/utils/formatUtil";
import { CameraContext } from "../Cameras/CameraProvider";
import PoQcStockInModal from "./PoQcStockInModal";
import QrModal from "./QrModal";
import { PlayArrow } from "@mui/icons-material";
import DoneIcon from "@mui/icons-material/Done";
import { downloadFile, getCustomWidth } from "@/app/utils/commonUtil";
import PoInfoCard from "./PoInfoCard";
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
import { List, ListItem, ListItemButton, ListItemText, Divider } from "@mui/material";
import { Controller, FormProvider, useForm } from "react-hook-form";
import dayjs, { Dayjs } from "dayjs";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker, LocalizationProvider, zhHK } from "@mui/x-date-pickers";
import { debounce } from "lodash";
import LoadingComponent from "../General/LoadingComponent";
import { getMailTemplatePdfForStockInLine } from "@/app/api/mailTemplate/actions";
import { PrinterCombo } from "@/app/api/settings/printer";
import { EscalationCombo } from "@/app/api/user";
//import { useRouter } from "next/navigation";


type Props = {
  po: PoResult;
  qc: QcItemWithChecks[];
  warehouse: WarehouseResult[];
  printerCombo: PrinterCombo[];
};

type EntryError =
  | {
    [field in keyof StockInLine]?: string;
  }
  | undefined;
// type PolRow = TableRow<Partial<StockInLine>, EntryError>;
const PoSearchList: React.FC<{
  poList: PoResult[];
  selectedPoId: number;
  onSelect: (po: PoResult) => void;
}> = ({ poList, selectedPoId, onSelect }) => {
  const { t } = useTranslation("purchaseOrder");
  const [searchTerm, setSearchTerm] = useState('');

  const filteredPoList = useMemo(() => {
    if (searchTerm.trim() === '') {
      return poList;
    }
    return poList.filter(poItem => 
      poItem.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      poItem.supplier?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      t(`${poItem.status.toLowerCase()}`).toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [poList, searchTerm, t]);

  return (
    <Paper sx={{ p: 2, maxHeight: "480px", overflow: "auto", minWidth: "300px", height: "480px" }}>
      <Typography variant="h6" gutterBottom>
        {t("Purchase Order")}
      </Typography>
      <TextField
        label={t("Search")}
        variant="outlined"
        size="small"
        fullWidth
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        sx={{ mb: 2 }}
        InputProps={{
          startAdornment: (
            <Typography variant="body2" color="text.secondary" sx={{ mr: 1 }}>
              
            </Typography>
          ),
        }}
      />
      {(filteredPoList.length > 0)? (
        <List dense sx={{ width: '100%' }}>
          {filteredPoList.map((poItem, index) => (
            <div key={poItem.id}>
              <ListItem disablePadding sx={{ width: '100%' }}>
                <ListItemButton
                  selected={selectedPoId === poItem.id}
                  onClick={() => onSelect(poItem)}
                  sx={{
                    width: '100%',
                    "&.Mui-selected": {
                      backgroundColor: "primary.light",
                      "&:hover": {
                        backgroundColor: "primary.light",
                      },
                    },
                  }}
                >
                  <ListItemText
                    primary={
                      <Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
                        {poItem.code}
                      </Typography>
                    }
                    secondary={
                      <Typography variant="caption" color="text.secondary">
                        {t(`${poItem.status.toLowerCase()}`)}
                      </Typography>
                    }
                  />
                </ListItemButton>
              </ListItem>
              {index < filteredPoList.length - 1 && <Divider />}
            </div>
          ))}
        </List>) : (
          <LoadingComponent/>
        )
      }
      {searchTerm && (
        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: "block" }}>
          {`${t("Found")} ${filteredPoList.length} ${t("Purchase Order")}`}
          {/* {`${t("Found")} ${filteredPoList.length} of ${poList.length} ${t("Item")}`} */}
        </Typography>
      )}
    </Paper>
  );
};

interface PolInputResult {
  lotNo: string,
  dnQty: number,
}

const PoDetail: React.FC<Props> = ({ po, qc, warehouse, printerCombo }) => {
  const cameras = useContext(CameraContext);
  // console.log(cameras);
  const { t } = useTranslation("purchaseOrder");
  const apiRef = useGridApiRef();
  const [purchaseOrder, setPurchaseOrder] = useState({ ...po });
  const [rows, setRows] = useState<PurchaseOrderLine[]>(
    purchaseOrder.pol || [],
  );
  const [polInputList, setPolInputList] = useState<PolInputResult[]>([])
  useEffect(() => {
    setPolInputList(
      (purchaseOrder.pol ?? []).map(() => ({
        lotNo: "",
        dnQty: 0,
      } as PolInputResult))
    );
  }, [purchaseOrder.pol]);

  const pathname = usePathname()
  const searchParams = useSearchParams();
  
  const [selectedRow, setSelectedRow] = useState<PurchaseOrderLine | null>(null);
  const defaultPolId = searchParams.get("polId")
  useEffect(() => {
    if (defaultPolId) {
        setSelectedRow(rows.find((r) => r.id.toString() === defaultPolId) ?? null)
        console.log("%c StockIn:", "color:green", selectedRow);
    }
  }, [])

  const [stockInLine, setStockInLine] = useState<StockInLine[]>([]);
  const [processedQty, setProcessedQty] = useState(0);

  const router = useRouter();
  const [poList, setPoList] = useState<PoResult[]>([]);
  const [selectedPoId, setSelectedPoId] = useState(po.id);
  const [focusField, setFocusField] = useState<HTMLInputElement>();

  const currentPoId = searchParams.get('id');
  const selectedIdsParam = searchParams.get('selectedIds');
  // const [selectedRowId, setSelectedRowId] = useState<number | null>(null);
  const dnFormProps = useForm({
    defaultValues: {
      dnNo: '',
      dnDate: dayjsToDateString(dayjs())
    }
  })
  const fetchPoList = useCallback(async () => {
    try {
      if (selectedIdsParam) {

        const selectedIds = selectedIdsParam.split(',').map(id => parseInt(id));
        const promises = selectedIds.map(id => fetchPoInClient(id));
        const results = await Promise.all(promises);
        setPoList(results.filter(Boolean));
      } else {

        const result = await fetchPoListClient({ limit: 20, offset: 0 });
        if (result && result.records) {
          setPoList(result.records);
        }
      }
    } catch (error) {
      console.error("Failed to fetch PO list:", error);
    }
  }, [selectedIdsParam]);


   const fetchPoDetail = useCallback(async (poId: string) => {
    try {
      const result = await fetchPoInClient(parseInt(poId));
      console.log(result)
      if (result) {
        console.log("%c Fetched PO:", "color:orange", result);
        setPurchaseOrder(result);
        setRows(result.pol || []);
        if (result.pol && result.pol.length > 0) {
          if (result.id === selectedPoId) {
            const polIndex = result.pol.findIndex((p) => p.id === selectedRow?.id)
            // setSelectedRow(result.pol[polIndex]);
            setStockInLine(result.pol[polIndex].stockInLine);
            setProcessedQty(result.pol[polIndex].processed);
          } else {
            // setSelectedRow(result.pol[0]);
            setStockInLine(result.pol[0].stockInLine);
            setProcessedQty(result.pol[0].processed);
          }
        }
        // if (focusField) {console.log(focusField);focusField.focus();}
      }
    } catch (error) {
      console.error("Failed to fetch PO detail:", error);
    }
  }, [selectedRow]);
  
  const handlePoSelect = useCallback(
    async (selectedPo: PoResult) => {
      if (selectedPo.id === selectedPoId) return;
      setSelectedPoId(selectedPo.id);
      await fetchPoDetail(selectedPo.id.toString());
      const newSelectedIds = selectedIdsParam || selectedPo.id.toString();
      // router.push(`/po/edit?id=${selectedPo.id}&start=true&selectedIds=${newSelectedIds}`, { scroll: false });
      const newUrl = `/po/edit?id=${selectedPo.id}&start=true&selectedIds=${newSelectedIds}`;
      if (pathname + searchParams.toString() !== newUrl) {
        router.replace(newUrl, { scroll: false });
      }
    },
    [router, selectedIdsParam, fetchPoDetail]
  );
  
  useEffect(() => {
    if (currentPoId && currentPoId !== selectedPoId.toString()) {
      setSelectedPoId(parseInt(currentPoId));
      fetchPoDetail(currentPoId);
    }
  }, [currentPoId, fetchPoDetail]);

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

  useEffect(() => {
    if (currentPoId) {
      setSelectedPoId(parseInt(currentPoId));
    }
  }, [currentPoId]);

  const removeParam = (paramToRemove: string) => {
    const newParams = new URLSearchParams(searchParams.toString());
    newParams.delete(paramToRemove);
    window.history.replaceState({}, '', `${window.location.pathname}?${newParams}`);
  };

  const handleCompletePo = useCallback(async () => {
    const checkRes = await checkPolAndCompletePo(purchaseOrder.id);
    console.log(checkRes);
    const newPo = await fetchPoInClient(purchaseOrder.id);
    setPurchaseOrder(newPo);
  }, [purchaseOrder.id]);

  const handleStartPo = useCallback(async () => {
    const startRes = await startPo(purchaseOrder.id);
    console.log(startRes);
    const newPo = await fetchPoInClient(purchaseOrder.id);
    setPurchaseOrder(newPo);
  }, [purchaseOrder.id]);

  const handleMailTemplateForStockInLine = useCallback(async (stockInLineId: number) => {
    const response = await getMailTemplatePdfForStockInLine(stockInLineId)
    if (response) {
      downloadFile(new Uint8Array(response.blobValue), response.filename);
    }
  }, [])

  useEffect(() => {
    setRows(purchaseOrder.pol || []);
  }, [purchaseOrder]);

  // useEffect(() => {
  //   setStockInLine([])
  // }, []);

  function Row(props: { row: PurchaseOrderLine }) {
    const { row } = props;
    // const [firstReceiveQty, setFirstReceiveQty] = useState<number>()
    // const [secondReceiveQty, setSecondReceiveQty] = useState<number>()
    // const [open, setOpen] = useState(false);
    const [processedQty, setProcessedQty] = useState(row.processed);
    const [currStatus, setCurrStatus] = useState(row.status);
    // const [stockInLine, setStockInLine] = useState(row.stockInLine);
    const totalWeight = useMemo(
      () => calculateWeight(row.qty, row.uom),
      [row.qty, row.uom],
    );
    const weightUnit = useMemo(
      () => returnWeightUnit(row.uom),
      [row.uom],
    );
    const rowIndex = useMemo(() => {
      return rows.findIndex((r) => r.id === row.id)
    }, [])

    useEffect(() => {
      const polId = searchParams.get("polId") != null ? parseInt(searchParams.get("polId")!) : null
      if (polId) {
        setStockInLine(rows.find((r) => r.id == polId)!.stockInLine)
      }
    }, []);

    useEffect(() => {
      if (processedQty === row.qty) {
        setCurrStatus("completed".toUpperCase());
      } else if (processedQty > 0) {
        setCurrStatus("receiving".toUpperCase());
      } else {
        setCurrStatus("pending".toUpperCase());
      }
    }, [processedQty, row.qty]);

    const handleRowSelect = () => {
      // setSelectedRowId(row.id);
      setSelectedRow(row);
      setStockInLine(row.stockInLine);
      setProcessedQty(row.processed);
    };
    const changeStockInLines = useCallback(
        (id: number) => {
          //rows = purchaseOrderLine
          const target = rows.find((r) => r.id === id)
          const stockInLine = target!.stockInLine
          setStockInLine(stockInLine)
          setSelectedRow(target!)
          // console.log(pathname)
          // router.replace(`/po/edit?id=${item.poId}&polId=${item.polId}&stockInLineId=${item.stockInLineId}`);
        },
        [rows]
      );

    const handleStart = useCallback(
      () => {
        setTimeout(async () => {
          // post stock in line
          const oldId = row.id;
          const acceptedQty = Number(polInputList[rowIndex].dnQty);
          if (isNaN(acceptedQty) || acceptedQty <= 0) { alert("來貨數量必須大於0！"); return; }  // Temp check, need update

          const postData = {
            dnNo: dnFormProps.watch("dnNo"),
            dnDate: outputDateStringToInputDateString(dnFormProps.watch("dnDate")),
            itemId: row.itemId,
            itemNo: row.itemNo,
            itemName: row.itemName,
            purchaseOrderId: row.purchaseOrderId,
            purchaseOrderLineId: row.id,
            acceptedQty: acceptedQty,
            productLotNo: polInputList[rowIndex].lotNo || '',
            // acceptedQty: secondReceiveQty || 0,
            // acceptedQty: row.acceptedQty,
          };
          // if (secondReceiveQty === 0) return
          const res = await createStockInLine(postData);
          if (res) {
            fetchPoDetail(selectedPoId.toString());
          }
          console.log(res);
        }, 200);
      },
      [polInputList, row, dnFormProps],
    );

    const handleChange = useCallback(debounce((e: React.ChangeEvent<HTMLInputElement>) => {
      const raw = e.target.value;
      const id = e.target.id
      // const temp = polInputList
      switch (id) {
        case "lotNo":
          if (raw.trim() === '') {
            polInputList[rowIndex].lotNo = '';
            break;
          }
          polInputList[rowIndex].lotNo = raw.trim();
          break;
        case "dnQty":
           // Allow empty input
          if (raw.trim() === '') {
            polInputList[rowIndex].dnQty = 0;
            break;
          }

          // Keep digits only
          const cleaned = raw.replace(/[^\d]/g, '');
          if (cleaned === '') {
            // If the user typed only non-digits, keep previous value
            break;
          }

          // Parse and clamp to non-negative integer
          const next = Math.max(0, Math.floor(Number(cleaned)));
          polInputList[rowIndex].dnQty = next;
          break;
        default:
          break;
      }
      // setPolInputList(() => temp)
    }, 300), [rowIndex]);

    // const [focusField, setFocusField] = useState<HTMLInputElement>();

    const purchaseToStockRatio = (row.stockUom.purchaseRatioN ?? 1) / (row.stockUom.purchaseRatioD ?? 1) * (row.stockUom.stockRatioD ?? 1) / (row.stockUom.stockRatioN ?? 1)
    return (
      <>
        <TableRow 
          sx={{ "& > *": { borderBottom: "unset" }, 
          color: "black" 
          }}
          onClick={() => changeStockInLines(row.id)}
          >
          {/* <TableCell>
            <IconButton
              disabled={purchaseOrder.status.toLowerCase() === "pending"}
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          </TableCell> */}
          <TableCell align="center" sx={{ width: '60px' }}>
            <Radio
              checked={selectedRow?.id === row.id}
              // onChange={handleRowSelect}
              // onClick={(e) => e.stopPropagation()}
            />
          </TableCell>
          <TableCell align="left">{row.itemNo}</TableCell>
          <TableCell align="left">{row.itemName}</TableCell>
          <TableCell align="right">{integerFormatter.format(row.qty)}</TableCell>
          <TableCell align="right">{integerFormatter.format(row.processed)}</TableCell>
          <TableCell align="left">{row.uom?.udfudesc}</TableCell>
          {/* <TableCell align="right">{decimalFormatter.format(row.stockUom.stockQty)}</TableCell> */}
          <TableCell align="right">{decimalFormatter.format(row.stockInLine.filter((sil) => sil.purchaseOrderLineId === row.id).reduce((acc, cur) => acc + (cur.acceptedQty ?? 0),0) * purchaseToStockRatio)}</TableCell>
          <TableCell align="left">{row.stockUom.stockUomDesc}</TableCell>
          {/* <TableCell align="right">
            {decimalFormatter.format(totalWeight)} {weightUnit}
          </TableCell> */}
          {/* <TableCell align="left">{weightUnit}</TableCell> */}
          {/* <TableCell align="right">{decimalFormatter.format(row.price)}</TableCell> */}
          {/* <TableCell align="left">{row.expiryDate}</TableCell> */}
          <TableCell align="left">{t(`${currStatus.toLowerCase()}`)}</TableCell>
          {/* <TableCell align="right">{integerFormatter.format(row.receivedQty)}</TableCell> */}
          <TableCell align="center">
            <TextField
              id="lotNo"
              label="輸入貨品批號"
              type="text" // Use type="text" to allow validation in the change handler
              variant="outlined"
              defaultValue={polInputList[rowIndex]?.lotNo ?? ''}
              onChange={handleChange}
              // onFocus={(e) => {setFocusField(e.target as HTMLInputElement);}}
            />
          </TableCell>
          <TableCell align="center">
            <TextField
              id="dnQty"
              label="此批送貨數量"
              type="text" // Use type="text" to allow validation in the change handler
              variant="outlined"
              defaultValue={polInputList[rowIndex]?.dnQty ?? ''}
              onChange={handleChange}
              InputProps={{
                inputProps: {
                  min: 0, // Optional: set a minimum value
                  step: 1  // Optional: set the step for the number input
                }
              }}
            />
          </TableCell>
          <TableCell align="center">
            <Button 
              variant="contained"
              onClick={() => 
                handleStart()
              }
              >
              {t("submit")}
            </Button>
          </TableCell>
        </TableRow>
        {/* <TableRow> */}
          {/* <TableCell /> */}
          {/* <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={12}> */}
            {/* <Collapse in={true} timeout="auto" unmountOnExit> */}
              {/* <Collapse in={open} timeout="auto" unmountOnExit> */}
              {/* <Table>
                <TableBody>
                  <TableRow>
                    <TableCell align="right">
                      <Box>
                        <PoInputGrid
                          qc={qc}
                          setRows={setRows}
                          stockInLine={stockInLine}
                          setStockInLine={setStockInLine}
                          setProcessedQty={setProcessedQty}
                          itemDetail={row}
                          warehouse={warehouse}
                        />
                      </Box>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table> */}
            {/* </Collapse> */}
          {/* </TableCell> */}
        {/* </TableRow> */}
      </>
    );
  }
// ROW END

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

  const [isOpenScanner, setOpenScanner] = useState(false);
  // const testing = useCallback(() => {
  //   // setOpenScanner(true);
  //   const newParams = new URLSearchParams(searchParams.toString());
  //   console.log(pathname)
  // }, [pathname, router, searchParams]);

  const onOpenScanner = useCallback(() => {
    setOpenScanner(true);
  }, []);

  const onCloseScanner = useCallback(() => {
    setOpenScanner(false);
  }, []);

  const [itemInfo, setItemInfo] = useState<
    StockInLine & { warehouseId?: number }
  >();
  const [putAwayOpen, setPutAwayOpen] = useState(false);
  // const [scannedInfo, setScannedInfo] = useState<QrCodeInfo>({} as QrCodeInfo);

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

  const buttonData = useMemo(() => {
    switch (purchaseOrder.status.toLowerCase()) {
      case "pending":
        return {
          buttonName: "start",
          title: t("Do you want to start?"),
          confirmButtonText: t("Start"),
          successTitle: t("Start Success"),
          errorTitle: t("Start Fail"),
          buttonText: t("Start PO"),
          buttonIcon: <PlayArrow />,
          buttonColor: "success",
          disabled: false,
          onClick: handleStartPo,
        };
      case "receiving":
        return {
          buttonName: "complete",
          title: t("Do you want to complete?"),
          confirmButtonText: t("Complete"),
          successTitle: t("Complete Success"),
          errorTitle: t("Complete Fail"),
          buttonText: t("Complete PO"),
          buttonIcon: <DoneIcon />,
          buttonColor: "info",
          disabled: false,
          onClick: handleCompletePo,
        };
      default:
        return {
          buttonName: "complete",
          title: t("Do you want to complete?"),
          confirmButtonText: t("Complete"),
          successTitle: t("Complete Success"),
          errorTitle: t("Complete Fail"),
          buttonText: t("Complete PO"),
          buttonIcon: <DoneIcon />,
          buttonColor: "info",
          disabled: true,
        };
      // break;
    }
  }, [purchaseOrder.status, t, handleStartPo, handleCompletePo]);

  const FIRST_IN_FIELD = "firstInQty"
  const SECOND_IN_FIELD = "secondInQty"

  const renderFieldCondition = useCallback((field: "firstInQty" | "secondInQty"): boolean => {
    switch (field) {
      case FIRST_IN_FIELD:
        return true;
      case SECOND_IN_FIELD:
        return true;
      default:
        return false; // Default case
    }
  }, []);

  useEffect(() => {
    const params = searchParams.get("polId")
    if (params) {
      const polId = parseInt(params)

    }
  }, [searchParams])

  const handleDatePickerChange = useCallback((value: Dayjs | null, onChange: (...event: any[]) => void) => {
    if (value != null) {
        const updatedValue = dayjsToDateString(value)
        onChange(updatedValue)
    } else {
        onChange(value)
    }
}, [])

  return (
    <>
      <Stack spacing={2}>
        {/* Area1: title */}
        <Grid container xs={12} justifyContent="start">
          <Grid item>
            <Typography mb={2} variant="h4">
              {purchaseOrder.code} -{" "}
              {t(`${purchaseOrder.status.toLowerCase()}`)}
            </Typography>
          </Grid>
        </Grid>

        {/* area2: dn info */}
        <Grid container spacing={3} sx={{ maxWidth: 'fit-content' }}>
          {/* left side select po */}
          <Grid item xs={4}>
            <PoSearchList
              poList={poList}
              selectedPoId={selectedPoId}
              onSelect={handlePoSelect}
            />
          </Grid>

          {/* right side po info */}
          <Grid item xs={8}>
            <Grid container spacing={3} sx={{ maxWidth: 'fit-content' }}>
              <Grid item xs={12}>
                <PoInfoCard po={purchaseOrder} />
              </Grid>
              <Grid item xs={12}>
                {true ? (
                <FormProvider {...dnFormProps}>
                  <Stack component={"form"} spacing={2}>
                    <Card sx={{ display: "block", height: "230px" }}>
                      <CardContent component={Stack} spacing={2}>
                        <Grid container spacing={2} sx={{ maxWidth: 'fit-content' }}>
                          <Grid item xs={12}>
                            <TextField
                              {...dnFormProps.register("dnNo")}
                              label={t("dnNo")}
                              type="text"
                              variant="outlined"
                              fullWidth
                              // InputProps={{
                              //   inputProps: {
                              //     min: 0,
                              //     step: 1
                              //   }
                              // }}
                            />
                          </Grid>
                          <Grid item xs={12}>
                          <LocalizationProvider
                                    dateAdapter={AdapterDayjs}
                                    // TODO: Should maybe use a custom adapterLocale here to support YYYY-MM-DD
                                    adapterLocale="zh-hk"
                                    localeText={zhHK.components.MuiLocalizationProvider.defaultProps.localeText}
                                  >
                              <Controller
                                control={dnFormProps.control}
                                name="dnDate"
                                render={({ field }) => (
                                  
                                    <DatePicker
                                      label={t("dnDate")}
                                      format={`${OUTPUT_DATE_FORMAT}`}
                                      defaultValue={dateStringToDayjs(field.value)}
                                      onChange={(newValue: Dayjs | null) => {
                                        handleDatePickerChange(newValue, field.onChange)
                                      }}
                                      slotProps={{ textField: { fullWidth: true }}}
                                    />
                                )}
                                />
                                  </LocalizationProvider>
                          </Grid>
                          {/* <TextField
                            label={t("dnDate")}
                            type="text"
                            variant="outlined"
                            defaultValue={"11/08/2025"}
                            fullWidth
                          /> */}
                        </Grid>
                    {/* <Button variant="contained" onClick={onOpenScanner} fullWidth>
                      提交
                    </Button> */}
                      </CardContent>
                    </Card>
                  </Stack>
                </FormProvider>
              ) : undefined}
              </Grid>
            </Grid>
          </Grid>
        </Grid>



        {/* Area4: Main Table */}
        <Grid container xs={12} justifyContent="start">
          <Grid item xs={12}>
            <TableContainer component={Paper} sx={{ width: 'fit-content', overflow: 'auto' }}>
              <Table aria-label="collapsible table" stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell align="center" sx={{ width: '60px' }}></TableCell>
                    <TableCell sx={{ width: '125px' }}>{t("itemNo")}</TableCell>
                    <TableCell align="left" sx={{ width: '125px' }}>{t("itemName")}</TableCell>
                    <TableCell align="right">{t("qty")}</TableCell>
                    <TableCell align="right">{t("processedQty")}</TableCell>
                    <TableCell align="left">{t("uom")}</TableCell>
                    <TableCell align="right">{t("receivedTotal")}</TableCell>
                    <TableCell align="left">{t("Stock UoM")}</TableCell>
                    {/* <TableCell align="right">{t("total weight")}</TableCell> */}
                    {/* <TableCell align="right">{`${t("price")} (HKD)`}</TableCell> */}
                    <TableCell align="left" sx={{ width: '75px' }}>{t("status")}</TableCell>
                    {/* {renderFieldCondition(FIRST_IN_FIELD) ? <TableCell align="right">{t("receivedQty")}</TableCell> : undefined} */}
                    <TableCell align="center" sx={{ width: '150px' }}>{t("productLotNo")}</TableCell>
                    {renderFieldCondition(SECOND_IN_FIELD) ? <TableCell align="center" sx={{ width: '150px' }}>{t("dnQty")}<br/>(以訂單單位計算)</TableCell> : undefined}
                    <TableCell align="center" sx={{ width: '100px' }}></TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {rows.map((row) => (
                    <Row key={row.id} row={row} />
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Grid>
        </Grid>

        {/* area5: selected item info */}
        <Grid container xs={12} justifyContent="start">
          <Grid item xs={12}>
            <Typography variant="h6">
              {selectedRow ? `已選擇貨品: ${selectedRow?.itemNo ? selectedRow.itemNo : 'N/A'} - ${selectedRow?.itemName ? selectedRow?.itemName : 'N/A'}` : "未選擇貨品"}
            </Typography>
          </Grid>
          <Grid item xs={12}>
            {selectedRow && (
              <TableContainer component={Paper} sx={{ width: 'fit-content', overflow: 'auto' }}>
                <Table>
                  <TableBody>
                    <TableRow>
                      <TableCell align="right">
                        <Box>
                          <PoInputGrid
                            qc={qc}
                            setRows={setRows}
                            stockInLine={stockInLine}
                            setStockInLine={setStockInLine}
                            setProcessedQty={setProcessedQty}
                            itemDetail={selectedRow}
                            warehouse={warehouse}
                            fetchPoDetail={fetchPoDetail}
                            handleMailTemplateForStockInLine={handleMailTemplateForStockInLine}
                            printerCombo={printerCombo}
                          />
                        </Box>
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Grid>
        </Grid>
        {/* tab 2 */}
        <Grid sx={{ display: tabIndex === 1 ? "block" : "none" }}>
          {/* <StyledDataGrid
          
          /> */}
        </Grid>
      </Stack>
      {/* {itemInfo !== undefined && (
        <>
          <PoQcStockInModal
            type={"putaway"}
            open={putAwayOpen}
            warehouse={warehouse}
            setItemDetail={setItemInfo}
            onClose={closePutAwayModal}
            itemDetail={itemInfo}
          />
        </>
      )} */}
    </>
  );
};
export default PoDetail;