import { ContextModalProps } from "@mantine/modals";
import { Button, Flex, rem, TextInput } from "@mantine/core";
import { useEffect, useState } from "react";
import { ProductService } from "../../client";

type Props = {
    productId: number;
    onSubmit: (barcode: string) => void;
};
const PrintBarcodeModal = ({
    id,
    context,
    innerProps,
}: ContextModalProps<Props>) => {
    const { productId, onSubmit } = innerProps;
    const [barcode, setBarcode] = useState<string | undefined>();
    const [isBarcodeExist, setIsBarcodeExist] = useState<boolean>(true);

    const getErrorMessage = () => {
        if (!barcode) return "Штрихкод не может быть пустым";
        if (isBarcodeExist) return "Штрихкод уже существует";
        return undefined;
    };
    useEffect(() => {
        if (!barcode) return;
        ProductService.existsProductBarcode({
            productId: innerProps.productId,
            barcode: barcode.trim(),
        }).then(response => {
            setIsBarcodeExist(response.exists);
        });
    }, [productId, barcode]);

    const onSubmitClick = () => {
        if (!barcode || isBarcodeExist) return;
        onSubmit(barcode.trim());
        context.closeModal(id);
    };
    return (
        <Flex
            gap={rem(10)}
            direction={"column"}>
            <TextInput
                required
                error={getErrorMessage()}
                label={"Штрихкод"}
                placeholder={"Введите или отсканируйте штрихкод"}
                value={barcode}
                onChange={event => setBarcode(event.currentTarget.value)}
            />
            <Button
                onClick={onSubmitClick}
                disabled={!barcode || isBarcodeExist}>
                Добавить
            </Button>
        </Flex>
    );
};

export default PrintBarcodeModal;
