import { IconCheck, IconTrash, IconX } from "@tabler/icons-react";
import { DepartmentService, UserDepartmentSectionSchema } from "../../../../../client";
import { DataTableColumn } from "mantine-datatable";
import { ActionIcon, Box, Flex, Tooltip } from "@mantine/core";
import { useDepartmentContext } from "../contexts/DepartmentContext.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";

type Props = {
    sectionId: number;
}

const useUsersTableColumns = ({ sectionId }: Props) => {
    const { fetchDepartments } = useDepartmentContext();

    const onDeleteUserClick = (userId: number) => {
        DepartmentService.deleteUser({
            requestBody: {
                sectionId,
                userId,
            },
        })
            .then(({ ok, message }) => {
                fetchDepartments();
                if (ok) return;
                notifications.error({ message });
            })
            .catch(err => console.log(err));
    };

    return [
        {
            title: "ФИО",
            accessor: "user.secondName",
            render: (userData) => (
                <Box component="span">
                    <span>{userData.user.secondName} {userData.user.firstName} {userData.user.patronymic}</span>
                </Box>
            ),
        },
        {
            accessor: "user.role.name",
            title: "Роль",
        },
        {
            accessor: "user.position.name",
            title: "Должность",
        },
        {
            accessor: "user.comment",
            title: "Доп. информация",
        },
        {
            accessor: "isChief",
            title: "Является руководителем",
            render: (userData) =>
                userData.isChief ? (
                    <IconCheck />
                ) : (
                    <IconX />
                ),
        },
        {
            accessor: "actions",
            title: "",
            width: "0%",
            render: (userData) => (
                <Flex gap="md" mx={"md"}>
                    <Tooltip label="Удалить">
                        <ActionIcon
                            onClick={() => onDeleteUserClick(userData.user.id)}
                            variant={"default"}>
                            <IconTrash />
                        </ActionIcon>
                    </Tooltip>
                </Flex>
            ),
        },
    ] as DataTableColumn<UserDepartmentSectionSchema>[];
};

export default useUsersTableColumns;
