"use client";

import {
  Button,
  ButtonProps,
  Card,
  CardContent,
  CardHeader,
  CircularProgress,
  Grid,
  Stack,
  Typography,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import { useCallback, useEffect, useMemo, useState } from "react";
import { GridColDef } from "@mui/x-data-grid";
import { PlayArrow } from "@mui/icons-material";
import DoneIcon from "@mui/icons-material/Done";
import { GridRowSelectionModel } from "@mui/x-data-grid";
import { useQcCodeScanner } from "../QrCodeScannerProvider/QrCodeScannerProvider";
import { fetchPickOrderLineClient } from "@/app/api/pickorder/actions";
import { PickOrderLineWithSuggestedLot } from "@/app/api/pickorder";
import { Pageable } from "@/app/utils/fetchUtil";
import { QrCodeInfo } from "@/app/api/qrcode";
import { QrCode } from "../QrCode";
import { fetchLotDetail, LotLineInfo } from "@/app/api/inventory/actions";
import { GridRowModesModel } from "@mui/x-data-grid";

interface Props {
  consoCode: string;
}
interface IsLoadingModel {
  pickOrderLineTable: boolean;
  stockOutLineTable: boolean;
}

const PickOrderDetail: React.FC<Props> = ({ consoCode }) => {
  const { t } = useTranslation("pickOrder");
  const [selectedRow, setSelectRow] = useState<GridRowSelectionModel>();
  const [isLoadingModel, setIsLoadingModel] = useState<IsLoadingModel>({
    pickOrderLineTable: false,
    stockOutLineTable: false,
  });
  const [polCriteriaArgs, setPolCriteriaArgs] = useState<Pageable>({
    pageNum: 1,
    pageSize: 10,
  });
  const [solCriteriaArgs, setSolCriteriaArgs] = useState<Pageable>({
    pageNum: 1,
    pageSize: 10,
  });
  const [polTotalCount, setPolTotalCount] = useState(0);
  const [solTotalCount, setSolTotalCount] = useState(0);
  const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});

  const [pickOrderLine, setPickOrderLine] = useState<
    PickOrderLineWithSuggestedLot[]
  >([]);

  const pickOrderLineColumns = useMemo<GridColDef[]>(
    () => [
      {
        field: "id",
        headerName: "pickOrderLineId",
        flex: 1,
      },
      {
        field: "itemName",
        headerName: "itemId",
        flex: 1,
      },
      {
        field: "qty",
        headerName: "qty",
        flex: 1,
      },
      {
        field: "uom",
        headerName: "uom",
        flex: 1,
      },
      {
        field: "warehouse",
        headerName: "location",
        flex: 1,
      },
      {
        field: "suggestedLotNo",
        headerName: "suggestedLotNo",
        flex: 1.2,
      },
    ],
    []
  );
  const [stockOutLine, setStockOutLine] = useState([]);
  const stockOutLineColumns = useMemo<GridColDef[]>(
    () => [
      {
        field: "code",
        headerName: "actual lot (out line",
        flex: 1,
      },
    ],
    []
  );

  const handleStartPickOrder = useCallback(async () => {}, []);

  const handleCompletePickOrder = useCallback(async () => {}, []);

  useEffect(() => {
    console.log(selectedRow);
  }, [selectedRow]);

  const buttonData = useMemo(
    () => ({
      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,
    }),
    []
  );

  const [isOpenScanner, setOpenScanner] = useState(false);
  const onOpenScanner = useCallback(() => {
    setOpenScanner((prev) => !prev);
  }, []);

  const fetchPickOrderLine = useCallback(
    async (params: Record<string, any>) => {
      setIsLoadingModel((prev) => ({
        ...prev,
        pickOrderLineTable: true,
      }));
      const res = await fetchPickOrderLineClient({
        ...params,
        consoCode: consoCode,
      });
      if (res) {
        console.log(res);
        setPickOrderLine(res.records);
        setPolTotalCount(res.total);
      } else {
        console.log("error");
        console.log(res);
      }
      setIsLoadingModel((prev) => ({
        ...prev,
        pickOrderLineTable: false,
      }));
    },
    [fetchPickOrderLineClient, consoCode]
  );
  const fetchStockOutLine = useCallback(
    async (params: Record<string, any>) => {},
    []
  );

  useEffect(() => {
    fetchPickOrderLine(polCriteriaArgs);
  }, [polCriteriaArgs]);

  useEffect(() => {
    fetchStockOutLine(solCriteriaArgs);
  }, [solCriteriaArgs]);

  const getLotDetail = useCallback(
    async (stockInLineId: number): Promise<LotLineInfo> => {
      const res = await fetchLotDetail(stockInLineId);
      return res;
    },
    [fetchLotDetail]
  );

  const scanner = useQcCodeScanner();
  useEffect(() => {
    if (isOpenScanner && !scanner.isScanning) {
      scanner.startScan();
    } else if (!isOpenScanner && scanner.isScanning) {
      scanner.stopScan();
    }
  }, [isOpenScanner]);

  useEffect(() => {
    if (scanner.values.length > 0) {
      console.log(scanner.values[0]);
      const data: QrCodeInfo = JSON.parse(scanner.values[0]);
      console.log(data);
      if (data.stockInLineId) {
        console.log("still got in");
        console.log(data.stockInLineId);
        // fetch
        getLotDetail(data.stockInLineId).then((value) => {});
      }
      scanner.resetScan();
    }
  }, [scanner.values]);

  const homemade_Qrcode = {
    stockInLineId: 156,
  };

  return (
    <>
      <Stack spacing={2}>
        <Grid container xs={12} justifyContent="start">
          <Grid item xs={12}>
            <Typography variant="h4" marginInlineEnd={2}>
              {consoCode}
            </Typography>
          </Grid>
          <Grid item xs={8}>
            <Button
              // onClick={buttonData.onClick}
              disabled={buttonData.disabled}
              color={buttonData.buttonColor as ButtonProps["color"]}
              startIcon={buttonData.buttonIcon}
            >
              {buttonData.buttonText}
            </Button>
          </Grid>
          <Grid
            item
            xs={4}
            display="flex"
            justifyContent="end"
            alignItems="end"
          >
            <Button onClick={onOpenScanner}>
              {isOpenScanner ? t("binding") : t("bind")}
            </Button>
          </Grid>
          {/* homemade qrcode for testing purpose */}
          {/* <Grid
            item
            xs={12}
            style={{ display: "flex", justifyContent: "center" }}
          >
            <QrCode
              content={homemade_Qrcode}
              sx={{ width: 200, height: 200 }}
            />
          </Grid> */}
        </Grid>
        <Grid container xs={12} justifyContent="space-between">
          {/* <Grid item xs={12} sx={{ height: 400 }}>
            <StyledDataGrid rows={pickOrderLine} columns={columns} />
          </Grid> */}
          <Grid item xs={12} sx={{ height: 400 }}>
            {isLoadingModel.pickOrderLineTable ? (
              <CircularProgress size={40} />
            ) : (
              <StyledDataGrid
                rows={pickOrderLine}
                columns={pickOrderLineColumns}
                rowSelectionModel={selectedRow}
                onRowSelectionModelChange={(newRowSelectionModel) => {
                  setSelectRow(newRowSelectionModel);
                }}
                initialState={{
                  pagination: {
                    paginationModel: { pageSize: 10, page: 0 },
                  },
                }}
                pageSizeOptions={[10, 25, 50, 100]}
                onPaginationModelChange={async (model, details) => {
                  setPolCriteriaArgs({
                    pageNum: model.page + 1,
                    pageSize: model.pageSize,
                  });
                }}
                rowCount={polTotalCount}
              />
            )}
          </Grid>
          <Grid item xs={12} sx={{ height: 400 }}>
            <StyledDataGrid
              rows={stockOutLine}
              columns={stockOutLineColumns}
              rowModesModel={rowModesModel}
              onRowModesModelChange={setRowModesModel}
              disableColumnMenu
              editMode="row"
              // processRowUpdate={processRowUpdate}
              // onProcessRowUpdateError={onProcessRowUpdateError}

              initialState={{
                pagination: {
                  paginationModel: { pageSize: 10, page: 0 },
                },
              }}
              pageSizeOptions={[10, 25, 50, 100]}
              onPaginationModelChange={async (model, details) => {
                setSolCriteriaArgs({
                  pageNum: model.page + 1,
                  pageSize: model.pageSize,
                });
              }}
              rowCount={solTotalCount}
            />
          </Grid>
        </Grid>
      </Stack>
    </>
  );
};
export default PickOrderDetail;
