import { notifications } from "../../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import { useCardPageContext } from "../../../contexts/CardPageContext.tsx";
import { CardEmployeesSchema, CardService } from "../../../../../client";

const useEmployeesTab = () => {
    const { selectedCard: card, refetchCard } = useCardPageContext();

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

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

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

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

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

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

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

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

export default useEmployeesTab;
