import {ContextModalProps, modals} from "@mantine/modals";
import {Button, Divider, Flex, NumberInput, rem, Select} from "@mantine/core";
import {useEffect, useRef, useState} from "react";
import {BarcodeSchema, ProductService} from "../../client";
import {useGetProductById} from "../../api/product/useGetProductById.tsx";
import {notifications} from "../../shared/lib/notifications.ts";
import PrintBarcodeContainer from "./PrintBarcodeContainer.tsx";
import {base64ToBlob} from "../../shared/lib/utils.ts";

type Props = {
    productId: number;
    defaultQuantity?: number;
}
const PrintBarcodeModal = ({
                               innerProps
                           }: ContextModalProps<Props>) => {
    const {productId, defaultQuantity = 1} = innerProps;
    const [quantity, setQuantity] = useState(defaultQuantity);
    const [barcode, setBarcode] = useState<string | undefined>()
    const [barcodeData, setBarcodeData] = useState<BarcodeSchema | undefined>();

    const {product, refetch} = useGetProductById(productId);

    const barcodeRef = useRef(null);
    // const handlePrint = useReactToPrint({
    //     content: () => barcodeRef.current
    // });

    const onAdd = (newBarcode: string) => {
        ProductService.addProductBarcode({requestBody: {productId, barcode: newBarcode}})
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
            })
    }
    const onAddClick = () => {
        if (!product) return;
        modals.openContextModal({
            modal: "addBarcode",
            title: 'Добавление штрихкода',
            withCloseButton: true,
            innerProps: {
                productId: product.id,
                onSubmit: onAdd
            }
        })
    }

    const onGenerateClick = () => {
        if (!product) return;
        ProductService.generateProductBarcode({requestBody: {productId}})
            .then(async ({ok, message, barcode}) => {
                notifications.guess(ok, {message});
                if (!ok) return;
                await refetch();
                setBarcode(barcode);
            })
    }
    const fetchBarcodeData = () => {
        if (!barcode) return;
        ProductService.getProductBarcode({
            requestBody:
                {barcode, productId}
        }).then(({barcode}) => {
            setBarcodeData(barcode);
        })
    }
    useEffect(() => {
        if (!product) return;
        if (product.barcodes.length === 1)
            setBarcode(product.barcodes[0]);
    }, [product]);

    useEffect(() => {
        if (!barcode) return;
        fetchBarcodeData();
    }, [barcode]);

    return (
        <>
            <Flex
                gap={rem(10)}
                direction={"column"}
            >
                <Select
                    value={barcode}
                    onChange={(value) => setBarcode(value || undefined)}
                    data={product?.barcodes}
                    label={"Штрихкод"}
                    placeholder={"Выберите штрихкод"}
                />
                <NumberInput
                    label={"Количество копий"}
                    placeholder={"Введите количество копий"}
                    value={quantity}
                    onChange={(value) => typeof value === "number" && setQuantity(value)}
                    min={1}
                />

                <Divider
                    my={rem(10)}
                />
                <Flex direction={"column"} gap={rem(10)}>
                    <Flex gap={rem(10)}>
                        <Button
                            onClick={() => onAddClick()}
                            variant={"default"}
                            fullWidth>
                            Добавить вручную
                        </Button>
                        <Button
                            onClick={() => onGenerateClick()}
                            variant={"default"}
                            fullWidth>
                            Сгенерировать
                        </Button>
                    </Flex>
                    <Button
                        size={"lg"}
                        disabled={!barcode}
                        onClick={async () => {
                            if (!barcode) return;
                            const response = await ProductService.getProductBarcodePdf({
                                requestBody: {
                                    productId,
                                    barcode,
                                    quantity
                                }
                            });
                            const pdfBlob = base64ToBlob(response.base64String, response.mimeType);
                            const pdfUrl = URL.createObjectURL(pdfBlob);
                            const pdfWindow = window.open(pdfUrl);
                            if (!pdfWindow) {
                                notifications.error({message: "Ошибка"});
                                return
                            }
                            pdfWindow.onload = () => {
                                pdfWindow.print();
                            }
                        }}
                    >Печать</Button>
                </Flex>
            </Flex>
            <PrintBarcodeContainer
                barcode={barcode}
                quantity={quantity}
                ref={barcodeRef}
                attributes={barcodeData?.attributes || []}
                additionalField={barcodeData?.additionalField}
            />
        </>
    )
}

export default PrintBarcodeModal;