import { useState } from "react";
import { useWindowEvent } from "@mantine/hooks";

export type ScanningData = {
    boxId?: number;
    palletId?: number;
    isScanning: boolean;
}

type Props = {
    onScanningFinish: (value: string, boxId?: number, palletId?: number) => void;
}

const useScanningMode = ({ onScanningFinish }: Props) => {
    const [scanningValue, setScanningValue] = useState<string>("");
    const [boxId, setBoxId] = useState<number>();
    const [palletId, setPalletId] = useState<number>();
    const [isScanning, setIsScanning] = useState<boolean>(false);

    const setIsScanningValue = (isScanning: boolean) => {
        if (!isScanning) {
            setScanningValue("");
            setBoxId(undefined);
            setPalletId(undefined);
        }
        setIsScanning(isScanning);
    };

    useWindowEvent("keydown", (event) => {
        if (!isScanning) return;
        event.preventDefault();
        setScanningValue(prevState => prevState + event.key);
        if (["\n", "\r", "Enter"].includes(event.key)) {
            onScanningFinish(scanningValue, boxId, palletId);
            setScanningValue("");
        }
    });

    const toggleScanning = (boxId?: number, palletId?: number) => {
        if (isScanning) {
            setBoxId(undefined);
            setPalletId(undefined);
        } else {
            setBoxId(boxId);
            setPalletId(palletId);
        }
        setIsScanningValue(!isScanning);
        setScanningValue("");
    };

    const scanningData: ScanningData = {
        boxId,
        palletId,
        isScanning,
    };

    return {
        scanningData,
        toggleScanning,
    };
};

export default useScanningMode;
