import { WorkShiftsService } from "../../../../../client";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";

type Props = {
    fetchShifts: () => void;
}

enum InputType {
    START_SHIFT,
    FINISH_SHIFT,
    RESUME_SHIFT,
    PAUSE_SHIFT,
}

const useWorkShiftInput = ({ fetchShifts }: Props) => {
    let inputType: InputType = InputType.START_SHIFT;

    const workShiftMethods = {
        [InputType.START_SHIFT]: WorkShiftsService.startShift,
        [InputType.FINISH_SHIFT]: WorkShiftsService.finishShift,
        [InputType.RESUME_SHIFT]: WorkShiftsService.finishPauseByUserId,
        [InputType.PAUSE_SHIFT]: WorkShiftsService.startPauseByUserId,
    };

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

        workShiftMethods[inputType]({ userId })
            .then(async ({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchShifts();
            })
            .catch(err => console.log(err));
    };

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

    const onShiftStart = () => {
        inputType = InputType.START_SHIFT;
        onScanningStart();
    };

    const onShiftFinish = () => {
        inputType = InputType.FINISH_SHIFT;
        onScanningStart();
    };

    const onShiftResume = () => {
        inputType = InputType.RESUME_SHIFT;
        onScanningStart();
    };

    const onShiftPause = () => {
        inputType = InputType.PAUSE_SHIFT;
        onScanningStart();
    };

    return {
        onShiftStart,
        onShiftFinish,
        onShiftResume,
        onShiftPause,
    };
};

export default useWorkShiftInput;
