"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,
} 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,
  fetchStockInLineInfo,
  PurchaseQcResult,
  startPo,
} 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 { useSearchParams } from "next/navigation";
import { WarehouseResult } from "@/app/api/warehouse";
import { calculateWeight, 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 { getCustomWidth } from "@/app/utils/commonUtil";
import PoInfoCard from "./PoInfoCard";
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";

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

type EntryError =
  | {
    [field in keyof StockInLine]?: string;
  }
  | undefined;
// type PolRow = TableRow<Partial<StockInLine>, EntryError>;
const PoDetail: React.FC<Props> = ({ po, qc, warehouse }) => {
  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 searchParams = useSearchParams();
  // const [currPoStatus, setCurrPoStatus] = useState(purchaseOrder.status);

  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]);

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

  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],
    );

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

    return (
      <>
        <TableRow sx={{ "& > *": { borderBottom: "unset" }, color: "black" }}>
          <TableCell>
            <IconButton
              disabled={purchaseOrder.status.toLowerCase() === "pending"}
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          </TableCell>
          <TableCell align="left">{row.itemNo}</TableCell>
          <TableCell align="left">{row.itemName}</TableCell>
          <TableCell align="left">{integerFormatter.format(row.qty)}</TableCell>
          <TableCell align="left">{integerFormatter.format(processedQty)}</TableCell>
          <TableCell align="left">{row.uom?.code}</TableCell>
          <TableCell align="left">
            {decimalFormatter.format(totalWeight)} {weightUnit}
          </TableCell>
          {/* <TableCell align="left">{weightUnit}</TableCell> */}
          <TableCell align="left">{decimalFormatter.format(row.price)}</TableCell>
          {/* <TableCell align="left">{row.expiryDate}</TableCell> */}
          <TableCell align="left">{t(`${currStatus.toLowerCase()}`)}</TableCell>
          {/* <TableCell align="left">
            0
          </TableCell>
          <TableCell align="left">
            <TextField
              label="輸入數量"
              type="text" // Use type="text" to allow validation in the change handler
              variant="outlined"
              value={secondReceiveQty}
              // onChange={handleChange}
              InputProps={{
                inputProps: {
                  min: 0, // Optional: set a minimum value
                  step: 1  // Optional: set the step for the number input
                }
              }}
            />
          </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>
      </>
    );
  }
  const [tabIndex, setTabIndex] = useState(0);
  const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    [],
  );

  const [isOpenScanner, setOpenScanner] = useState(false);
  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
    }
  }, []);

  return (
    <>
      <Stack
        spacing={2}
      //   component="form"
      //   onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        <Grid container xs={12} justifyContent="start">
          <Grid item>
            <Typography mb={2} variant="h4">
              {/* {purchaseOrder.code} - {currPoStatus} */}
              {purchaseOrder.code} -{" "}
              {t(`${purchaseOrder.status.toLowerCase()}`)}
            </Typography>
          </Grid>
        </Grid>
        {false ? (<Grid container xs={12} justifyContent="start">
          <Grid item xs={3}>
            <TextField
              label={t("dnNo")}
              type="text" // Use type="text" to allow validation in the change handler
              variant="outlined"
              // value={secondReceiveQty}
              // onChange={handleChange}
              InputProps={{
                inputProps: {
                  min: 0, // Optional: set a minimum value
                  step: 1  // Optional: set the step for the number input
                }
              }}
            />
          </Grid>
          <Grid item xs={3}>
            <TextField
              label={t("dnDate")}
              type="text" // Use type="text" to allow validation in the change handler
              variant="outlined"
              defaultValue={"07/08/2025"}
              // value={secondReceiveQty}
              // onChange={handleChange}
              InputProps={{
                inputProps: {
                  min: 0, // Optional: set a minimum value
                  step: 1  // Optional: set the step for the number input
                }
              }}
            />
            {/* <Button
              onClick={buttonData.onClick}
              disabled={buttonData.disabled}
              color={buttonData.buttonColor as ButtonProps["color"]}
              startIcon={buttonData.buttonIcon}
            >
              {buttonData.buttonText}
            </Button> */}
          </Grid>
          <Grid
            item
            xs={6}
            display="flex"
            justifyContent="end"
            alignItems="end"
          >
            <Button onClick={onOpenScanner}>{t("Accept submit")}</Button>
          </Grid>
        </Grid>) : undefined}
        <Grid container xs={12} justifyContent="space-between">
          
          {/* <Grid item xs={4}> */}
          {/* scanner */}
          {/* </Grid> */}
          <Grid
            item
            xs={4}
            display="flex"
            justifyContent="end"
            alignItems="end"
          >
            <QrModal
              open={isOpenScanner}
              onClose={onCloseScanner}
              warehouse={warehouse}
            />
            {/* <Button onClick={onOpenScanner}>{t("Accept submit")}</Button> */}
            {/* <Button onClick={onOpenScanner}>{t("bind")}</Button> */}
          </Grid>
        </Grid>
        {/* tab 1 */}
        <Grid rowSpacing={2} container sx={{ display: tabIndex === 0 ? "block" : "none" }}>
          <Grid item xs={12}>
            <PoInfoCard po={purchaseOrder} />
          </Grid>
          <Grid item xs={12}>
            <TableContainer component={Paper} sx={{ width: 'fit-content', overflow: 'auto' }}>
              {/* <TableContainer component={Paper} sx={{width: getCustomWidth(), overflow: 'auto' }}> */}
              <Table aria-label="collapsible table" stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell /> {/* for the collapse button */}
                    <TableCell>{t("itemNo")}</TableCell>
                    <TableCell align="left">{t("itemName")}</TableCell>
                    <TableCell align="left">{t("qty")}</TableCell>
                    <TableCell align="left">{t("processed")}</TableCell>
                    <TableCell align="left">{t("uom")}</TableCell>
                    <TableCell align="left">{t("total weight")}</TableCell>
                    {/* <TableCell align="left">{t("weight unit")}</TableCell> */}
                    <TableCell align="left">{`${t("price")} ($)`}</TableCell>
                    {/* <TableCell align="left">{t("expiryDate")}</TableCell> */}
                    <TableCell align="left">{t("status")}</TableCell>
                    {/* start == true && firstInQty == null ? no hide : hide*/}
                    {/* {renderFieldCondition(FIRST_IN_FIELD) ? <TableCell align="left">{t("receivedQty")}</TableCell> : undefined} */}
                    {/* start == true && firstInQty == null ? hide and disabled : no hide*/}
                    {/* {renderFieldCondition(SECOND_IN_FIELD) ? <TableCell align="left">{t("dnQty")}</TableCell> : undefined} */}
                    {/* <TableCell align="left">{"add icon button"}</TableCell> */}
                  </TableRow>
                </TableHead>
                <TableBody>
                  {rows.map((row) => (
                    <Row key={row.id} row={row} />
                  ))}
                </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;
