import {UserSchema} from "../../../../client";
import {FC} from "react";
import {BaseTable} from "../../../../components/BaseTable/BaseTable.tsx";
import {useSimpleUsersTableColumns} from "./columns.tsx";
import {MRT_TableOptions} from "mantine-react-table";
import {ActionIcon, Button, Flex, rem, Tooltip} from "@mantine/core";
import {modals} from "@mantine/modals";
import {IconTrash} from "@tabler/icons-react";
import {UserRoleEnum} from "../../../../shared/enums/UserRole.ts";

export type SimpleUsersTableProps = {
    items: UserSchema[],
    onChange: (items: UserSchema[]) => void
}

const SimpleUsersTable: FC<SimpleUsersTableProps> = ({items, onChange}) => {
    const columns = useSimpleUsersTableColumns();

    const onAddClick = () => {
        const userIds = items.map(user => user.id);
        modals.openContextModal({
            title: "Выберите сотрудника",
            modal: "employeeSelect",
            withCloseButton: false,
            innerProps: {
                selectProps: {
                    filterBy: (user) => !userIds.includes(user.id) && user.roleKey === UserRoleEnum.EMPLOYEE
                },
                onSelect: (user) => onChange([...items, user])
            }
        })
    }

    return (
        <BaseTable
            data={items}
            columns={columns}
            restProps={{
                enableColumnActions: false,
                enableSorting: false,
                enableBottomToolbar: true,
                renderBottomToolbar: (
                    <Flex justify={"flex-end"} gap={rem(10)} p={rem(10)}>
                        <Button onClick={() => onAddClick()} variant={"default"}>
                            Добавить сотрудника к услуге
                        </Button>
                    </Flex>
                ),
                enableRowActions: true,
                renderRowActions: ({row}) => (
                    <Tooltip label="Удалить">
                        <ActionIcon onClick={() => {
                            onChange(items.filter(item => item.id !== row.original.id));
                        }} variant={"default"}>
                            <IconTrash/>
                        </ActionIcon>
                    </Tooltip>),
            } as MRT_TableOptions<UserSchema>}
        />
    )
}

export default SimpleUsersTable;