"use client"; import { PlusCircle } from "lucide-react"; import { useTranslations } from "next-intl"; import { useCallback, useEffect, useRef, useState } from "react"; import { showToast } from "../../../../utils/toast"; import { useDebounce } from "../../../../hooks"; import { Button, Command, CommandDialog, CommandEmpty, CommandInput, CommandItem, CommandList, DialogDescription, DialogTitle, } from "../../../../shadcnui"; import { UserInterface } from "../../../user"; import { RoleInterface } from "../../data"; import { RoleService } from "../../data/role.service"; type UserRoleAddProps = { user: UserInterface; refresh: () => Promise; }; export function UserRoleAdd({ user, refresh }: UserRoleAddProps) { const [open, setOpen] = useState(false); const inputRef = useRef(null); const [searchTerm, setSearchTerm] = useState(""); const [roles, setRoles] = useState([]); const t = useTranslations(); const addUserToRole = async (role: RoleInterface) => { await RoleService.addUserToRole({ roleId: role.id, userId: user.id, }); setRoles(roles.filter((u) => u.id !== role.id)); showToast( t(`common.association.label`, { source: t(`entities.roles`, { count: 1 }), destination: t(`entities.users`, { count: 1 }), }), { description: t(`common.association.success`, { source: t(`entities.roles`, { count: 1 }), destination: t(`entities.users`, { count: 1 }), source_name: role.name, destination_name: user.name, }), }, ); refresh(); }; const searchRoles = useCallback( async (term: string) => { setRoles( await RoleService.findAllRolesUserNotIn({ search: term, userId: user.id, }), ); }, [searchTerm, user], ); const updateSearchTerm = useDebounce(searchRoles, 500); useEffect(() => { if (open) updateSearchTerm(searchTerm); }, [open, searchTerm]); useEffect(() => { if (open) searchRoles(""); }, [open]); return ( <> {t(`common.association.label`, { source: t(`entities.roles`, { count: 1 }), destination: t(`entities.users`, { count: 1 }), })} {t(`common.association.description`, { source: t(`entities.roles`, { count: 1 }), destination: t(`entities.users`, { count: 1 }), destination_name: user.name, })} {t(`ui.search.no_results`, { type: t(`entities.roles`, { count: 1 }) })} {roles.map((role: RoleInterface) => ( addUserToRole(role)} onClick={() => addUserToRole(role)} > {t(`role.roles`, { role: role.id.replaceAll(`-`, ``) })} ))} ); }