import { Button, Center, Stack, Text } from "@mantine/core";
import useScanning from "../../../hooks/useScanning.tsx";
import { useEffect } from "react";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import ReceiptPalletEditor from "./ReceiptPalletEditor.tsx";
import ReceiptBoxEditor from "./ReceiptBoxEditor.tsx";
import { IconArrowLeft } from "@tabler/icons-react";

const ReceiptQrCodeScan = () => {
    const {
        setIsScanning,
        scannedValue,
        setScannedValue,
    } = useScanning();

    useEffect(() => {
        setIsScanning(true);
    }, []);

    const getId = () => Number.parseInt(scannedValue.substring(1));

    const checkQrScannedCorrectly = () => {
        if (
            scannedValue.length < 2
            || (scannedValue[0] !== "P" && scannedValue[0] !== "K")
            || Number.isNaN(getId())
        ) {
            notifications.error({ message: `Считанный ID ${scannedValue} некорректный` });
            setScannedValue("");
            setIsScanning(true);
        }
    };

    useEffect(() => {
        if (scannedValue) {
            checkQrScannedCorrectly();
        }
    }, [scannedValue]);

    if (!scannedValue) {
        return (
            <Stack>
                <Button
                    variant={"default"}
                    onClick={() => window.location.reload()}
                >
                    <IconArrowLeft />
                </Button>
                <Center>
                    <Text>
                        Отсканируйте QR код
                    </Text>
                </Center>
            </Stack>
        );
    }

    if (scannedValue.length > 0 && scannedValue[0] === "K") {
        return <ReceiptBoxEditor boxId={getId()} />;
    }
    return <ReceiptPalletEditor palletId={getId()} />;
};

export default ReceiptQrCodeScan;
