"use client";

import {
  fetchPoWithStockInLines,
  PoResult,
  PurchaseOrderLine,
  StockInLine,
} from "@/app/api/po";
import {
  Box,
  Button,
  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,
  fetchStockInLineInfo,
  PurchaseQcResult,
  testFetch,
} from "@/app/api/po/actions";
import {
  use,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";
import { FormProvider, useForm } from "react-hook-form";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import InputDataGrid, {
  TableRow as InputTableRow,
} from "../InputDataGrid/InputDataGrid";
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 QrCodeScanner from "../QrCodeScanner";
import { CameraDevice, Html5Qrcode } from "html5-qrcode";
import { CameraContext } from "../Cameras/CameraProvider";
import StyledDataGrid from "../StyledDataGrid";
import { QrCodeInfo } from "@/app/api/qrcode";
import { fetchQcResult } from "@/app/api/qc/actions";
import PoQcStockInModal from "./PoQcStockInModal";
import ReactQrCodeScannerModal, {
  ScannerConfig,
} from "../ReactQrCodeScanner/ReactQrCodeScanner";
import QrModal from "./QrModal";

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();
  const apiRef = useGridApiRef();
  const [rows, setRows] = useState<PurchaseOrderLine[]>(po.pol || []);
  const params = useSearchParams();

  function Row(props: { row: PurchaseOrderLine }) {
    const { row } = props;
    const [open, setOpen] = useState(false);
    const [processedQty, setProcessedQty] = useState(row.processed);
    const [currStatus, setCurrStatus] = useState(row.status);
    useEffect(() => {
      if (processedQty === row.qty) {
        setCurrStatus("completed".toUpperCase());
      } else if (processedQty > 0) {
        setCurrStatus("receiving".toUpperCase());
      } else {
        setCurrStatus("pending".toUpperCase());
      }
    }, [processedQty]);

    const totalWeight = useMemo(
      () => calculateWeight(row.qty, row.uom),
      [calculateWeight]
    );
    const weightUnit = useMemo(
      () => returnWeightUnit(row.uom),
      [returnWeightUnit]
    );

    return (
      <>
        <TableRow sx={{ "& > *": { borderBottom: "unset" }, color: "black" }}>
          <TableCell>
            <IconButton
              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">{row.qty}</TableCell>
          <TableCell align="left">{processedQty}</TableCell>
          <TableCell align="left">{row.uom?.code}</TableCell>
          <TableCell align="left">
            {totalWeight} {weightUnit}
          </TableCell>
          {/* <TableCell align="left">{weightUnit}</TableCell> */}
          <TableCell align="left">{row.price}</TableCell>
          {/* <TableCell align="left">{row.expiryDate}</TableCell> */}
          <TableCell align="left">{currStatus}</TableCell>
        </TableRow>
        <TableRow>
          {/* <TableCell /> */}
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={12}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell align="right">
                      <Box>
                        <PoInputGrid
                          qc={qc}
                          setRows={setRows}
                          setProcessedQty={setProcessedQty}
                          itemDetail={row}
                          stockInLine={row.stockInLine}
                          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 handleComplete = useCallback(async () => {
    const res = await checkPolAndCompletePo(po.id)
    if (res.type === "completed") {
      // toast.success(res.message)
      console.log(res)
      return
    } 
    if (res.type === "receiving") {
      // toast.error(res.message)
      console.log(res)
      return 
    }
  }, [checkPolAndCompletePo]);

  return (
    <>
      <Stack
        spacing={2}
        //   component="form"
        //   onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
      >
        <Grid container xs={12} justifyContent="space-between">
          <Grid item>
            <Typography mb={2} variant="h4">
              {po.code}
            </Typography>
          </Grid>
        </Grid>
        {/* <Grid container xs={12} justifyContent="space-between">
          <Button onClick={handleComplete}>Complete</Button>
        </Grid> */}
        <Grid container xs={12} justifyContent="space-between">
          <Grid item xs={8}>
            <Tabs
              value={tabIndex}
              onChange={handleTabChange}
              variant="scrollable"
            >
              <Tab label={t("General")} iconPosition="end" />
              {/* <Tab label={t("Bind Storage")} iconPosition="end" /> */}
            </Tabs>
          </Grid>
          {/* <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}>bind</Button>
          </Grid>
        </Grid>
        {/* tab 1 */}
        <Grid sx={{ display: tabIndex === 0 ? "block" : "none" }}>
          <TableContainer component={Paper}>
            <Table aria-label="collapsible table">
              <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">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>
                  {/* <TableCell align="left">{"add icon button"}</TableCell> */}
                </TableRow>
              </TableHead>
              <TableBody>
                {rows.map((row) => (
                  <Row key={row.id} row={row} />
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </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;
