import { BaseTable } from "../../../../components/BaseTable/BaseTable.tsx";
import { useActiveShiftsTableColumns } from "./columns.tsx";
import { ActionIcon, Flex, Stack, Text, Title, Tooltip } from "@mantine/core";
import { IconCheck, IconTrash } from "@tabler/icons-react";
import { ActiveWorkShiftSchema, WorkShiftsService } from "../../../../client";
import { modals } from "@mantine/modals";
import { formatDate } from "../../../../types/utils.ts";
import { MRT_TableOptions } from "mantine-react-table";
import { notifications } from "../../../../shared/lib/notifications.ts";


type Props = {
    activeShifts: ActiveWorkShiftSchema[];
    fetchActiveShifts: () => void;
}

export const ActiveShiftsTable = ({ activeShifts, fetchActiveShifts }: Props) => {
    const columns = useActiveShiftsTableColumns();

    const onDelete = (workShift: ActiveWorkShiftSchema) => {
        WorkShiftsService.deleteWorkShift({
            shiftId: workShift.id,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchActiveShifts();
            })
            .catch(err => {
                console.log(err);
            });
    };

    const onDeleteClick = (workShift: ActiveWorkShiftSchema) => {
        modals.openConfirmModal({
            title: "Удаление записи о начале смены",
            children: (
                <Text size="sm">
                    Вы уверены что хотите удалить запись о начале смены работника{" "}
                    {workShift.user.firstName} {workShift.user.secondName} от{" "}
                    {formatDate(workShift.startedAt)}
                </Text>
            ),
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => onDelete(workShift),
        });
    };

    const onShiftFinish = (workShift: ActiveWorkShiftSchema) => {
        WorkShiftsService.finishWorkShiftById({
            shiftId: workShift.id,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchActiveShifts();
            })
            .catch(err => console.log(err));
    }

    const onShiftFinishClick = (workShift: ActiveWorkShiftSchema) => {
        modals.openConfirmModal({
            title: "Завершение смены",
            children: (
                <Text size="sm">
                    Вы уверены что хотите завершить смену работника{" "}
                    {workShift.user.firstName} {workShift.user.secondName} от{" "}
                    {formatDate(workShift.startedAt)}
                </Text>
            ),
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => onShiftFinish(workShift),
        });
    }

    return (
        <Stack mx={"xs"}>
            <Title order={4} mt={"md"}>
                Активные смены
            </Title>
            <BaseTable
                data={activeShifts}
                columns={columns}
                restProps={
                    {
                        enableRowActions: true,
                        enableSorting: true,
                        enableColumnActions: false,
                        renderRowActions: ({ row }) => (
                            <Flex gap="md">
                                <Tooltip label="Удалить">
                                    <ActionIcon
                                        onClick={() =>
                                            onDeleteClick(row.original)
                                        }
                                        variant={"default"}>
                                        <IconTrash />
                                    </ActionIcon>
                                </Tooltip>
                                <Tooltip label="Завершить смену">
                                    <ActionIcon
                                        onClick={() =>
                                            onShiftFinishClick(row.original)
                                        }
                                        variant={"default"}>
                                        <IconCheck />
                                    </ActionIcon>
                                </Tooltip>
                            </Flex>
                        ),
                    } as MRT_TableOptions<ActiveWorkShiftSchema>
                }
            />
        </Stack>
    );
};