import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import { Button, Divider, Flex, NumberInput, rem, Stack } from "@mantine/core";
import ProductSelect from "../../../../../components/ProductSelect/ProductSelect.tsx";
import { ReceiptBox, ReceiptPallet } from "../types/types.tsx";
import { ResidualModalForm } from "../../../../ResiduesPage/types/ResidualProductData.tsx";
import nextId from "../utils/nextId.ts";
import useScanning from "../../../hooks/useScanning.tsx";
import ScanBarcode from "../../ScanBarcode/ScanBarcode.tsx";
import { ProductSchema } from "../../../../../client";


type Props = {
    clientId: number;
    object: ReceiptBox | ReceiptPallet;
    setObjectData: (object: ReceiptBox | ReceiptPallet) => void;
    barcodesProductsMap: Map<string, ProductSchema[]>;
}

const NewReceiptModal = ({
                             context,
                             id,
                             innerProps,
                         }: ContextModalProps<Props>) => {
    const {
        clientId,
        setObjectData,
        object,
        barcodesProductsMap,
    } = innerProps;
    const { isScanning, setIsScanning, scannedValue, setScannedValue } = useScanning();

    const initialValues = {
        product: null,
        quantity: 1,
    };
    const form = useForm<ResidualModalForm>({
        initialValues,
        validate: {
            product: product => !product && "Необходимо выбрать товар",
            quantity: quantity => (!quantity || quantity === 0) && "Слишком мало товара",
        },
    });

    const onSubmit = () => {
        const productIdx = object.residualProducts.findIndex(p => p.product.id === form.values.product?.id);

        if (productIdx !== -1) {
            object.residualProducts[productIdx].quantity += form.values.quantity;
        } else {
            const id = nextId();
            const receiptProduct = {
                id,
                product: form.values.product!,
                quantity: form.values.quantity,
            };
            object.residualProducts.unshift(receiptProduct);
        }

        setObjectData(object);
        form.reset();
        context.closeContextModal(id);
    };

    const onProductAfterScanningSelect = (product?: ProductSchema) => {
        if (!product) {
            setScannedValue("");
            return;
        }

        const productIdx = object.residualProducts.findIndex(p => p.product.id === product.id);
        if (productIdx === -1) {
            form.setFieldValue("product", product);
        } else {
            object.residualProducts[productIdx].quantity++;
            setObjectData({ ...object });
            context.closeContextModal(id);
        }
        setScannedValue("");
    };

    return (
        <Flex
            direction={"column"}
            gap={rem(10)}
        >
            <form onSubmit={form.onSubmit(() => onSubmit())}>
                <Stack gap={rem(10)}>
                    <Divider />
                    <ProductSelect
                        label={"Товар"}
                        placeholder={"Выберите товар"}
                        {...form.getInputProps("product")}
                        clientId={clientId}
                        disabled={isScanning}
                    />
                    <NumberInput
                        label={"Количество"}
                        hideControls
                        {...form.getInputProps("quantity")}
                        min={1}
                        defaultValue={1}
                        disabled={isScanning}
                    />
                    <Button
                        variant={"default"}
                        type={"submit"}
                        disabled={isScanning}
                    >
                        Добавить
                    </Button>
                    <Divider />
                </Stack>
            </form>

            <ScanBarcode
                isScanning={isScanning}
                setIsScanning={setIsScanning}
                onProductSelect={onProductAfterScanningSelect}
                scannedValue={scannedValue}
                object={object}
                barcodesProductsMap={barcodesProductsMap}
            />
        </Flex>
    );
};

export default NewReceiptModal;
