"use client";

import {
    Box,
    Button,
    Paper,
    Grid,
    Modal,
    ModalProps,
    Stack,
    Typography,
  } from "@mui/material";
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  import ReactQrCodeScanner, {
    ScannerConfig,
  } from "../ReactQrCodeScanner/ReactQrCodeScanner";
  import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
  import { StockInLine } from "@/app/api/stockIn";
  import { WarehouseResult } from "@/app/api/warehouse";
  import { QrCodeInfo } from "@/app/api/qrcode";
  import { Check, QrCodeScanner, Warehouse } from "@mui/icons-material";
  import { useTranslation } from "react-i18next";
  import { usePathname, useRouter, useSearchParams } from "next/navigation";
  import { useQrCodeScannerContext } from "../QrCodeScannerProvider/QrCodeScannerProvider";
import PutAwayModal from "./PutAwayModal";
import { PutAwayRecord } from ".";
import PutAwayReviewGrid from "./PutAwayReviewGrid";

type Props = {
    warehouse : WarehouseResult[];
};

type ScanStatusType = "pending" | "scanning" | "retry";

const PutAwayScan: React.FC<Props> = ({ warehouse }) => {
    const { t } = useTranslation("putAway");
    const searchParams = useSearchParams();
    const pathname = usePathname();
    const router = useRouter();
    const deepLinkConsumedRef = useRef(false);

    const [scanDisplay, setScanDisplay] = useState<ScanStatusType>("pending");
    const [openPutAwayModal, setOpenPutAwayModal] = useState(false);
    const [scannedSilId, setScannedSilId] = useState<number>(0);    // TODO use QR code info
    const [scannedWareHouseId, setScannedWareHouseId] = useState<number>(0);    // TODO use QR code info
    const [putAwayHistory, setPutAwayHistory] = useState<PutAwayRecord[]>([]);

    // QR Code Scanner
    const scanner = useQrCodeScannerContext();
    useEffect(() => {
        if (!scanner.isScanning) {
            scanner.startScan();
        } else if (scanner.isScanning) {
            scanner.stopScan();
        }
    }, []);

    const resetScan = (error : string = "") => {
        if (error !== "") {
            console.log("%c Scan failed, error: ", "color:red", error);
            setScanDisplay("retry");
        } else {
            console.log("%c Scan reset", "color:red");
        }
        scanner.resetScan();
    };

    const openModal = () => {
        console.log("Scanned successfully and open modal");
        scanner.stopScan();
        console.log("%c Scanning stopped ", "color:cyan");
        setOpenPutAwayModal(true);
        setScanDisplay("pending");
    };
    
    const closeModal = () => {
        setScannedSilId(0);
        setScannedWareHouseId(0);
        setScanDisplay("pending");
        console.log("Modal Closed");
        scanner.startScan();
        console.log("%c Scanning started ", "color:cyan");
        setOpenPutAwayModal(false);
    }

    const addPutAwayHistory = (putAwayData: PutAwayRecord) => {
        console.log("%c Added new data to Putaway history: ", "color:orange", putAwayData);
        const newPutaway = { ...putAwayData, id: putAwayHistory.length + 1 };
        setPutAwayHistory([...putAwayHistory, newPutaway]); // Create a new array with the new row
        // putAwayHistory.push(putAwayData);
    };

    // 处理默认 warehouseId 的回调
    const handleSetDefaultWarehouseId = useCallback((warehouseId: number) => {
        if (scannedWareHouseId === 0) {
            setScannedWareHouseId(warehouseId);
            console.log("%c Set default warehouseId from item locationCode:", "color:green", warehouseId);
        }
    }, [scannedWareHouseId]);

    useEffect(() => {
        if (scannedSilId > 0) {
            openModal();
        }
    }, [scannedSilId]);

    const stockInLineIdQ = searchParams.get("stockInLineId");

    /** Deep link from nav alert: /putAway?stockInLineId=… */
    useEffect(() => {
        if (!stockInLineIdQ || deepLinkConsumedRef.current) return;
        const id = parseInt(stockInLineIdQ, 10);
        if (!Number.isFinite(id) || id <= 0) return;
        deepLinkConsumedRef.current = true;
        setScannedSilId((prev) => (prev === id ? prev : id));

        // Consume deep link once, then remove it from URL
        const nextParams = new URLSearchParams(searchParams.toString());
        nextParams.delete("stockInLineId");
        const nextQuery = nextParams.toString();
        router.replace(nextQuery ? `${pathname}?${nextQuery}` : pathname);
    }, [stockInLineIdQ, pathname, router, searchParams]);

    // Get Scanned Values
    useEffect(() => {
        if (scanner.result) {
            const data = scanner.result;
            if (scannedSilId == 0) {    // Initial State
                if (!isNaN(Number(data.value))) { setScannedSilId(Number(data.value)); }
                else if (data.stockInLineId) {
                    setScannedSilId(Number(data.stockInLineId));
                } else resetScan("Cannot read Stock In Line Id");
            } else {    // Processing
                if (!isNaN(Number(data.value))) { setScannedWareHouseId(Number(data.value)); }
                else if (data.warehouseId) {
                    setScannedWareHouseId(Number(data.warehouseId));
                } else resetScan("Cannot read Warehouse Id");
            }
        scanner.resetScan();
        }
    }, [scanner.result]);

    // Get Scanner State
    useEffect(() => {
        if (scanner.state) {
            //
        }
    }, [scanner.state]);

    const displayText = useMemo(() => {
        switch (scanner.state) {
            case "pending":
                return t("Pending scan");
            case "scanning":
                return t("Scanning");
            case "retry":
                return t("Rescan");
            default:
                return t("Pending scan");
        }
        // if (scanDisplay == "pending") {
        //     return t("Pending scan");
        // } else if (scanDisplay == "retry") {
        //     return t("Rescan");
        // }
    }, [scanner.state]);

    return (<>
        <Paper sx={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                textAlign: 'center',}}
        >
            <Typography variant="h4">
                {displayText}
            </Typography>
            <QrCodeScanner sx={{padding: "10px", fontSize : "150px"}}/>
            
        </Paper>
        {putAwayHistory.length > 0 && (<>
            <Typography variant="h5">
                {t("putAwayHistory")}
            </Typography>
            <PutAwayReviewGrid
                putAwayHistory={putAwayHistory}
            />
        </>)}
        <PutAwayModal
            open={openPutAwayModal}
            onClose={closeModal}
            warehouse={warehouse}
            stockInLineId={scannedSilId}
            warehouseId={scannedWareHouseId}
            scanner={scanner}
            addPutAwayHistory={addPutAwayHistory}
            onSetDefaultWarehouseId={handleSetDefaultWarehouseId}
        />
    </>)
}

export default PutAwayScan;