"use client";

import { useEffect, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Flex, NumberInput, Select } from "@mantine/core";
import { ContextModalProps } from "@mantine/modals";
import InlineButton from "@/components/ui/InlineButton/InlineButton";
import { ProductSchema } from "@/lib/client";
import { getProductBarcodePdfMutation } from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";
import base64ToBlob from "@/utils/base64ToBlob";

type Props = {
    product: ProductSchema;
    defaultQuantity?: number;
};

const PrintBarcodeModal = ({ innerProps }: ContextModalProps<Props>) => {
    const { product, defaultQuantity = 1 } = innerProps;
    const [quantity, setQuantity] = useState(defaultQuantity);
    const [barcode, setBarcode] = useState<string | null>(null);

    const getBarcodePdfMutation = useMutation({
        ...getProductBarcodePdfMutation(),
        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 printBarcode = () => {
        if (!barcode && !product.barcodeImageUrl) return;
        getBarcodePdfMutation.mutate({
            body: {
                barcode: barcode ?? "",
                quantity,
                productId: product.id,
            },
        });
    };

    useEffect(() => {
        if (product.barcodes?.length === 1) {
            setBarcode(product.barcodes[0]);
        }
    }, [product]);

    return (
        <Flex
            gap={"xs"}
            direction={"column"}>
            {product.barcodeImageUrl ? (
                <object
                    style={{
                        alignSelf: "center",
                        aspectRatio:
                            product.barcodeTemplate.size.width /
                            product.barcodeTemplate.size.height,
                        width: "240px",
                    }}
                    data={product.barcodeImageUrl}>
                    Ошибка загрузки штрихкода
                </object>
            ) : (
                <Select
                    value={barcode}
                    onChange={value => setBarcode(value)}
                    data={product?.barcodes}
                    label={"Штрихкод"}
                    placeholder={"Выберите штрихкод"}
                />
            )}
            <NumberInput
                label={"Количество копий"}
                placeholder={"Введите количество копий"}
                value={quantity}
                onChange={value => setQuantity(Number(value))}
                allowNegative={false}
                min={1}
            />
            <InlineButton
                disabled={!barcode && !product.barcodeImageUrl}
                mt={"xs"}
                onClick={printBarcode}>
                Печать
            </InlineButton>
        </Flex>
    );
};

export default PrintBarcodeModal;
