import React, { useEffect } from 'react'; import { useLanguage } from '@/contexts/LanguageContext'; import { useFormContext } from 'react-hook-form'; import { FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from '@/components/ui/form'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useQuery } from '@tanstack/react-query'; import { userService } from '@/services/userService'; import { Badge } from '@/components/ui/badge'; import { X, Users } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; export const AssignedUsersField = () => { const { t } = useLanguage(); const form = useFormContext(); // Ensure assigned_users is initialized as an array useEffect(() => { const currentValue = form.getValues('assigned_users'); // console.log("Initial assigned_users value:", currentValue); // Initialize as empty array if no value or invalid value if (!currentValue || !Array.isArray(currentValue)) { // console.log("Initializing assigned_users as empty array"); form.setValue('assigned_users', [], { shouldValidate: false, shouldDirty: true }); } }, [form]); //console.log("Current form values:", form.getValues()); //console.log("Current assigned_users:", form.getValues('assigned_users')); // Fetch users for the assignment dropdown const { data: users = [], isLoading } = useQuery({ queryKey: ['users'], queryFn: async () => { try { const usersList = await userService.getUsers(); // console.log("Fetched users for assignment:", usersList); return Array.isArray(usersList) ? usersList : []; } catch (error) { // console.error("Failed to fetch users:", error); return []; } }, staleTime: 300000 // Cache for 5 minutes to reduce API calls }); // Get the currently selected assigned users from the form const selectedUserIds = Array.isArray(form.watch('assigned_users')) ? form.watch('assigned_users') : []; // console.log("Selected user IDs:", selectedUserIds); // Function to add a user const addUser = (userId: string) => { const currentValues = Array.isArray(form.getValues('assigned_users')) ? [...form.getValues('assigned_users')] : []; if (!currentValues.includes(userId)) { // console.log("Adding user:", userId); form.setValue('assigned_users', [...currentValues, userId], { shouldValidate: true, shouldDirty: true }); } }; // Function to remove a user const removeUser = (userId: string) => { const currentValues = Array.isArray(form.getValues('assigned_users')) ? [...form.getValues('assigned_users')] : []; // console.log("Removing user:", userId); form.setValue( 'assigned_users', currentValues.filter(id => id !== userId), { shouldValidate: true, shouldDirty: true } ); }; // Get selected users data const selectedUsers = users.filter(user => selectedUserIds.includes(user.id)); // console.log("Matched selected users:", selectedUsers); // Function to get user initials from name const getUserInitials = (user: any): string => { if (user.full_name) { const nameParts = user.full_name.split(' '); if (nameParts.length > 1) { return `${nameParts[0][0]}${nameParts[1][0]}`.toUpperCase(); } return user.full_name.substring(0, 2).toUpperCase(); } return user.username.substring(0, 2).toUpperCase(); }; return ( ( {t('assignedPersonnel')}
{selectedUsers.length > 0 ? (
{selectedUsers.map((user) => ( {getUserInitials(user)} {user.full_name || user.username} ))}
) : (
{t('noAssignedUsers')}
)}
{t('assignedPersonnelDescription')}
)} /> ); };