import { ContextModalProps } from "@mantine/modals";
import { Text } from "@mantine/core";
import { useWindowEvent } from "@mantine/hooks";
import { useState } from "react";

type Props = {
    label: string;
    onScan: (value: string) => void;
    closeOnScan?: boolean;
};

const ScanningModal = ({
                           context,
                           id,
                           innerProps,
                       }: ContextModalProps<Props>) => {
    const [inputValues, setInputValues] = useState<string>("");

    const { label, onScan, closeOnScan } = innerProps;

    useWindowEvent("keydown", (event) => {
        event.preventDefault();
        setInputValues(prevState => prevState + event.key);
        if (["\n", "\r", "Enter"].includes(event.key)) {
            onScan(inputValues);
            setInputValues("");
            if (closeOnScan) {
                context.closeContextModal(id);
            }
        }
    });

    return (
        <Text>{label}</Text>
    );
};

export default ScanningModal;
