import { useDealPageContext } from "../../../contexts/DealPageContext.tsx";
import { CreateBoxInDealSchema, CreateBoxInPalletSchema, ShippingService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import { Text } from "@mantine/core";
import useUpdateDeal from "./useUpdateDeal.tsx";

const useShipping = () => {
    const { selectedDeal: deal } = useDealPageContext();
    const { update } = useUpdateDeal();
    const palletIds: string[] = [];

    const onCreatePalletClick = () => {
        if (!deal) return;

        ShippingService.createPallet({
            dealId: deal.id,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                update();
            })
            .catch(err => console.log(err));
    };

    const onDeletePallet = (palletId: number) => {
        ShippingService.deletePallet({
            palletId: palletId,
        })
            .then(({ ok, message }) => {
                if (!ok) notifications.guess(ok, { message });
                update();
            })
            .catch(err => console.log(err));
    };

    const onDeletePalletClick = (palletId: number) => {
        if (!deal) return;
        modals.openConfirmModal({
            title: "Удаление паллета",
            children: <Text size="sm">Вы уверены что хотите удалить паллет?</Text>,
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => onDeletePallet(palletId),
        });
    };

    const onCreateBox = (data: CreateBoxInPalletSchema | CreateBoxInDealSchema) => {
        ShippingService.updateBox({
            requestBody: {
                data,
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                update();
            })
            .catch(err => console.log(err));
    };

    const onCreateBoxInDealClick = () => {
        onCreateBox({ dealId: deal?.id ?? -1 });
    };

    const onCreateBoxInPallet = (palletId: number) => {
        onCreateBox({ palletId });
    };

    const onCreateShippingProduct = (palletId: number) => {
        if (!deal) return;
        modals.openContextModal({
            modal: "shippingProductModal",
            title: "Добавление товара на паллет",
            withCloseButton: false,
            innerProps: {
                deal,
                updateOnSubmit: update,
                isBox: false,
                shippingData: {
                    palletId,
                    productId: null,
                    quantity: null,
                },
            },
        });
    };

    return {
        onCreateBoxInDealClick,
        onCreateBoxInPallet,
        onCreateShippingProduct,
        onCreatePalletClick,
        onDeletePalletClick,
        palletIds,
    };
};

export default useShipping;
