import { ActionIcon, Group, Tooltip } from "@mantine/core";
import styles from "../../../../../../pages/CardsPage/ui/CardsPage.module.css";
import { CardSchema, CardService } from "../../../../../../client";
import { base64ToBlob } from "../../../../../../shared/lib/utils.ts";
import { notifications } from "../../../../../../shared/lib/notifications.ts";
import { IconBarcode, IconPrinter } from "@tabler/icons-react";


type Props = {
    card: CardSchema;
}

const PrintDealBarcodesButton = ({ card }: Props) => {
    return (
        <Group wrap={"nowrap"}>
            <Tooltip
                className={styles["print-deals-button"]}
                label={"Распечатать штрихкоды сделки"}
            >
                <ActionIcon
                    onClick={async () => {
                        const response =
                            await CardService.getCardProductsBarcodesPdf({
                                requestBody: {
                                    cardId: card.id,
                                },
                            });
                        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();
                        };
                    }}
                    variant={"default"}>
                    <IconBarcode />
                </ActionIcon>
            </Tooltip>
            <Tooltip label={"Распечатать сделку"}>
                <ActionIcon
                    onClick={() => {
                        const pdfWindow = window.open(
                            `${import.meta.env.VITE_API_URL}/card/tech-spec/${card.id}`,
                        );
                        if (!pdfWindow) return;
                        pdfWindow.print();
                    }}
                    variant={"default"}>
                    <IconPrinter />
                </ActionIcon>
            </Tooltip>
        </Group>
    );
};

export default PrintDealBarcodesButton;
