import { DepartmentSchema, DepartmentSectionSchema } from "../../../../../client";
import { IconEdit, IconPlaylistAdd, IconTrash, IconUserPlus } from "@tabler/icons-react";
import { ActionIcon, Flex, Tooltip } from "@mantine/core";
import React, { ReactNode } from "react";
import { useDepartmentContext } from "../contexts/DepartmentContext.tsx";


type Props = {
    element: DepartmentSectionSchema | DepartmentSchema,
    isSection: boolean,
    level?: number,
}

const DepartmentActions = ({ element, isSection, level = 1 }: Props) => {
    const {
        onCreateDepartmentClick,
        onUpdateDepartmentClick,
        onDeleteDepartmentClick,
        onAddUserClick,
    } = useDepartmentContext();

    const getAction = (label: string, func: () => void, icon: ReactNode) => {
        return (
            <Tooltip label={label} key={label}>
                <ActionIcon
                    variant={"default"}
                    onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
                        e.stopPropagation();
                        func();
                    }}
                >
                    {icon}
                </ActionIcon>
            </Tooltip>
        );
    };

    const actions = [
        isSection && (
            getAction(
                "Добавить пользователя в отдел",
                () => onAddUserClick(element as DepartmentSectionSchema),
                <IconUserPlus />,
            )
        ),
        level < 9 && getAction(
            "Добавить отдел",
            () => onCreateDepartmentClick(true, {
                departmentId: isSection ? null : element.id,
                parentDepartmentSectionId: isSection ? element.id : null,
                name: "",
            }),
            <IconPlaylistAdd />,
        ),
        getAction(
            "Редактировать",
            () => onUpdateDepartmentClick(element, isSection),
            <IconEdit />,
        ),
        getAction(
            "Удалить",
            () => onDeleteDepartmentClick(element, isSection),
            <IconTrash />,
        ),
    ];

    return (
        <Flex gap={"md"} mx={"md"} direction={"row"}>
            {...actions}
        </Flex>
    );
};

export default DepartmentActions;
