import { Button, Group } from "@mantine/core";
import { IconCheck } from "@tabler/icons-react";
import { useReceiptContext } from "../contexts/ReceiptContext.tsx";
import { type ProductAndQuantitySchema, ReceiptBoxSchema, ReceiptPalletSchema, ResiduesService } from "../../../../../client";
import { ReceiptBox, ReceiptPallet, ReceiptProduct } from "../types/types.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";

const FinishReceiptButton = () => {
    const { pallets, boxes, client, reset } = useReceiptContext();
    const finishReceiptDisabled = pallets.length === 0 && boxes.length === 0;

    const processProducts = (products: ReceiptProduct[]): ProductAndQuantitySchema[] => {
        return products.map(p => ({
            productId: p.product.id,
            quantity: p.quantity,
        }));
    };

    const processBoxes = (boxes: ReceiptBox[]): ReceiptBoxSchema[] => {
        return boxes.map(box => ({
            products: processProducts(box.residualProducts),
        }));
    };

    const processPallets = (pallets: ReceiptPallet[]): ReceiptPalletSchema[] => {
        return pallets.map(pallet => ({
            products: processProducts(pallet.residualProducts),
            boxes: processBoxes(pallet.boxes),
        }));
    };

    const finishReceipt = () => {
        if (!client) return;

        ResiduesService.receipt({
            requestBody: {
                clientId: client.id,
                pallets: processPallets(pallets),
                boxes: processBoxes(boxes),
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                if (!ok) return;
                reset();
            })
            .catch(err => console.log(err));
    };

    return (
        <Button
            variant="default"
            onClick={finishReceipt}
            disabled={finishReceiptDisabled}
        >
            <Group gap={"sm"}>
                <IconCheck />
                Завершить приемку
            </Group>
        </Button>
    );
};

export default FinishReceiptButton;
