import { useEffect, useState } from "react";
import { ResidualBoxSchema, ResiduesService } from "../../../../../client";
import { modals } from "@mantine/modals";
import useBarcodesProductsMap from "../../../hooks/useBarcodesProductsMap.tsx";
import useScanningMode from "../../../hooks/useScanningMode.tsx";
import useApplyingScannedResult from "./useApplyingScannedResult.tsx";


type Props = {
    boxId: number;
}

const useReceiptBox = ({ boxId }: Props) => {
    const [box, setBox] = useState<ResidualBoxSchema | null>(null);
    const [clientId, setClientId] = useState<number | null>(null);

    useEffect(() => {
        fetchBox(boxId);
    }, []);

    const fetchBox = (boxId?: number) => {
        const id = boxId ?? box?.id;
        if (!id) return;

        ResiduesService.getResidualBox({ boxId: id })
            .then(res => {
                setBox(res.box);
                setClientId(res.clientId);
            })
            .catch(err => console.log(err));
    };

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

    const { onScanningFinish } = useApplyingScannedResult({
        object: box,
        barcodesProductsMap,
        refetch: fetchBox,
    });

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

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

    return {
        box,
        fetchBox,
        clientId,
        onCreateProductClick,
        scanningData,
        toggleScanning,
    };
};

export default useReceiptBox;
