"use client";

import {
    Box,
    Button,
    Paper,
    Grid,
    Modal,
    ModalProps,
    Stack,
    Typography,
  } from "@mui/material";
  import { useCallback, useEffect, useMemo, 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 { 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" | "rescan";

const PutAwayScan: React.FC<Props> = ({ warehouse }) => {
    const { t } = useTranslation("putAway");
    
    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("rescan");
        } 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);
    };

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

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

    return (<>
        <Paper sx={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                textAlign: 'center',}}
        >
            <Typography variant="h4">
                {scanDisplay == "pending" ? t("Pending scan") : t("Rescan")}
            </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}
        />
    </>)
}

export default PutAwayScan;