import { Button, Group, Stack } from "@mantine/core";
import { ActiveWorkShiftSchema, WorkShiftsService } from "../../../../client";
import { useEffect, useState } from "react";
import { notifications } from "../../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import { ActiveShiftsTable } from "../../components/ActiveShiftsTable/ActiveShiftsTable.tsx";

export const WorkShiftsTab = () => {
    let inputType: "StartShift" | "FinishShift" = "StartShift";
    const [activeShifts, setActiveShifts] = useState<ActiveWorkShiftSchema[]>([]);

    const fetchActiveShifts = () => {
        WorkShiftsService.getActiveShifts()
            .then(res => {
                setActiveShifts(res.shifts);
            })
            .catch(err => console.log(err));
    }

    useEffect(() => {
        fetchActiveShifts();
    }, []);

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

        if (inputType === "StartShift") {
            WorkShiftsService.startShift({
                userId: userId!,
            })
                .then(async ({ ok, message }) => {
                    notifications.guess(ok, { message });
                    fetchActiveShifts();
                })
                .catch(err => console.log(err));
            return;
        }

        WorkShiftsService.finishShift({
            userId: userId!,
        })
            .then(async ({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchActiveShifts();
            })
            .catch(err => console.log(err));
    };

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

    const onShiftStart = () => {
        inputType = "StartShift";
        onScanningStart();
    };

    const onShiftFinish = () => {
        inputType = "FinishShift";
        onScanningStart();
    };

    return (
        <Stack>
            <Group ml={"xs"} mt={"xs"}>
                <Button variant={"default"} onClick={onShiftStart}>
                    Начать смену
                </Button>
                <Button variant={"default"} onClick={onShiftFinish}>
                    Закончить смену
                </Button>
            </Group>
            <ActiveShiftsTable
                activeShifts={activeShifts}
                fetchActiveShifts={fetchActiveShifts}
            />
        </Stack>
    );
};

