import { useMutation } from "@tanstack/react-query";
import { modals } from "@mantine/modals";
import { DealProductSchema } from "@/lib/client";
import { getDealBarcodesPdfMutation } from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";
import { useFulfillmentBaseContext } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";
import base64ToBlob from "@/utils/base64ToBlob";

const useBarcodePrintActions = () => {
    const { deal } = useFulfillmentBaseContext();

    const onPrintProductBarcodeClick = (dealProduct: DealProductSchema) => {
        modals.openContextModal({
            modal: "printBarcodeModal",
            title: "Печать штрихкода",
            withCloseButton: true,
            innerProps: {
                product: dealProduct.product,
                defaultQuantity: dealProduct.quantity,
            },
        });
    };

    const getBarcodePdfMutation = useMutation({
        ...getDealBarcodesPdfMutation(),
        onSuccess: response => {
            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();
        },
    });

    const onPrintDealBarcodesClick = () => {
        getBarcodePdfMutation.mutate({
            body: {
                dealId: deal.id,
            },
        });
    };

    return {
        onPrintProductBarcodeClick,
        onPrintDealBarcodesClick,
    };
};

export default useBarcodePrintActions;
