import { BaseTable } from "../../../../../components/BaseTable/BaseTable.tsx";
import { useShiftsTableColumns } from "../hooks/columns.tsx";
import { ActionIcon, Flex, Text, Tooltip } from "@mantine/core";
import { IconCheck, IconPlayerPause, IconPlayerPlay, IconTrash } from "@tabler/icons-react";
import { WorkShiftRowSchema, WorkShiftsService } from "../../../../../client";
import { modals } from "@mantine/modals";
import { formatDate } from "../../../../../types/utils.ts";
import { MRT_Row, MRT_TableOptions } from "mantine-react-table";
import { notifications } from "../../../../../shared/lib/notifications.ts";
import { ShiftsTableType } from "../../../components/ShiftsTableSegmentedControl/ShiftsTableSegmentedControl.tsx";
import { ReactNode } from "react";


type Props = {
    shifts: WorkShiftRowSchema[];
    fetchShifts: () => void;
    shiftsTableType: ShiftsTableType;
}

export const ShiftsTable = ({
                                shifts,
                                fetchShifts,
                                shiftsTableType,
                            }: Props) => {
    const isActiveShiftsTable = shiftsTableType === ShiftsTableType.ACTIVE;
    const columns = useShiftsTableColumns({ isActiveShiftsTable });

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

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

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

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

    const onShiftPauseClick = (workShiftRow: WorkShiftRowSchema) => {
        WorkShiftsService.startPauseByShiftId({
            shiftId: workShiftRow.workShift.id,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchShifts();
            })
            .catch(err => console.log(err));
    };

    const onShiftResumeClick = (workShiftRow: WorkShiftRowSchema) => {
        WorkShiftsService.finishPauseByShiftId({
            shiftId: workShiftRow.workShift.id,
        })
            .then(({ ok, message }) => {
                notifications.guess(ok, { message });
                fetchShifts();
            })
            .catch(err => console.log(err));
    };

    const getAction = (
        label: string,
        func: () => void,
        icon: ReactNode,
    ) => {
        return (
            <Tooltip label={label}>
                <ActionIcon
                    onClick={func}
                    variant={"default"}>
                    {icon}
                </ActionIcon>
            </Tooltip>
        );
    };

    const getRowActions = (row: MRT_Row<WorkShiftRowSchema>) => {
        const actions = [
            getAction("Удалить", () => onDeleteClick(row.original), <IconTrash />),
        ];

        if (isActiveShiftsTable) {
            actions.push(
                getAction(
                    "Завершить смену",
                    () => onShiftFinishClick(row.original),
                    <IconCheck />,
                ),
            );
            if (row.original.workShift.isPaused) {
                actions.push(
                    getAction(
                        "Продолжить смену",
                        () => onShiftResumeClick(row.original),
                        <IconPlayerPlay />,
                    ),
                );
            } else {
                actions.push(
                    getAction(
                        "Поставить смену на паузу",
                        () => onShiftPauseClick(row.original),
                        <IconPlayerPause />,
                    ),
                );
            }
        }

        return actions;
    };

    return (
        <BaseTable
            data={shifts}
            columns={columns}
            restProps={
                {
                    enableRowActions: true,
                    enableSorting: false,
                    enableColumnActions: false,
                    renderRowActions: ({ row }) => {
                        return (
                            <Flex gap="md">
                                {...getRowActions(row)}
                            </Flex>
                        );
                    },
                } as MRT_TableOptions<WorkShiftRowSchema>
            }
        />
    );
};