import { useEffect, useState } from "react";
import { ResidualPalletSchema, ResiduesService } from "../../../../../client";
import { modals } from "@mantine/modals";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import useBarcodesProductsMap from "../../../hooks/useBarcodesProductsMap.tsx";
import useApplyingScannedResult from "./useApplyingScannedResult.tsx";
import useScanningMode from "../../../hooks/useScanningMode.tsx";

type Props = {
    palletId: number;
}

const useReceiptPallet = ({ palletId }: Props) => {
    const [pallet, setPallet] = useState<ResidualPalletSchema | null>(null);
    const [clientId, setClientId] = useState<number | null>(null);

    useEffect(() => {
        fetchPallet(palletId);
    }, []);

    const fetchPallet = (palletId?: number) => {
        const id = palletId ?? pallet?.id;
        if (!id) return;

        ResiduesService.getResidualPallet({ palletId: id })
            .then(res => {
                setPallet(res.pallet);
                setClientId(res.clientId);
            })
            .catch(err => console.log(err));
    };

    const { barcodesProductsMap } = useBarcodesProductsMap({ clientId: clientId ?? -1 });

    const { onScanningFinish } = useApplyingScannedResult({
        object: pallet,
        barcodesProductsMap,
        refetch: fetchPallet,
    });

    const { scanningData, toggleScanning } = useScanningMode({ onScanningFinish });

    const onCreateProductClick = () => {
        if (!(pallet && clientId)) return;
        modals.openContextModal({
            modal: "receiptModal",
            title: "Добавление товара",
            withCloseButton: false,
            innerProps: {
                clientId,
                isBox: false,
                object: pallet,
                fetchObject: fetchPallet,
                barcodesProductsMap,
            },
        });
    };

    const onCreateBoxClick = () => {
        ResiduesService.createResidualBox({
            requestBody: {
                palletId,
                clientId: null,
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                }
                fetchPallet();
            })
            .catch(err => console.log(err));
    };

    return {
        pallet,
        fetchPallet,
        clientId,
        onCreateProductClick,
        onCreateBoxClick,
        barcodesProductsMap,
        scanningData,
        toggleScanning,
    };
};

export default useReceiptPallet;
