import { notifications } from "../../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import { useDealPageContext } from "../../../contexts/DealPageContext.tsx";
import { DealEmployeesSchema, DealService } from "../../../../../client";

const useEmployeesTab = () => {
    const { selectedDeal: deal, refetchDeal } = useDealPageContext();

    const manageEmployee = (dealId: number, userId: number, isAssign: boolean) => {
        DealService.manageEmployee({
            requestBody: {
                dealId,
                userId,
                isAssign,
            },
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                refetchDeal();
            })
            .catch((err) => console.log(err));
    };

    const onInputFinish = (userIdInput: string) => {
        const userId = parseInt(userIdInput);
        if (isNaN(userId)) {
            notifications.error({ message: "Ошибка, некорректные данные в QR-коде" });
            return;
        }

        if (!deal) return;
        manageEmployee(deal.id, userId, true);
    };

    const onAssignEmployeeByQrClick = () => {
        modals.openContextModal({
            modal: "scanningModal",
            innerProps: {
                label: "Отсканируйте QR-код",
                onScan: onInputFinish,
                closeOnScan: true,
            },
            withCloseButton: false,
        });
    };

    const onUnassignEmployeeClick = (assignment: DealEmployeesSchema) => {
        if (!deal) return;
        manageEmployee(deal.id, assignment.user.id, false);
    };

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

        modals.openContextModal({
            modal: "assignUserModal",
            title: `Назначение исполнителя`,
            withCloseButton: false,
            innerProps: {
                deal,
                manageEmployee,
            },
        });
    };

    return {
        onAssignEmployeeByQrClick,
        onAssignEmployeeManuallyClick,
        onUnassignEmployeeClick,
    };
};

export default useEmployeesTab;
