// AssignUsersModal - Modal for managing user assignments to a project

function AssignUsersModal({ project, users, onClose, onSuccess }) {
    const [assignments, setAssignments] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [selectedUser, setSelectedUser] = React.useState('');
    const [assigning, setAssigning] = React.useState(false);
    const [refreshKey, setRefreshKey] = React.useState(0);
    const [confirmRemove, setConfirmRemove] = React.useState(null); // { userId, userName }
    const toast = useToast();

    const loadAssignments = React.useCallback(async () => {
        setLoading(true);
        // Clear existing data first to force visual update
        setAssignments([]);
        
        // Small delay to ensure backend has committed changes
        await new Promise(resolve => setTimeout(resolve, 100));
        
        try {
            const data = await ApiUtils.getProjectAssignments(project.id);
            // Force new array reference with deep copy for React to detect changes
            setAssignments(data.map(a => ({ ...a, _key: Date.now() })));
            setRefreshKey(Date.now());
        } catch (err) {
            toast('Errore nel caricamento assegnazioni: ' + err.message, 'error');
        } finally {
            setLoading(false);
        }
    }, [project.id, toast]);

    React.useEffect(() => {
        loadAssignments();
    }, [loadAssignments]);

    const handleAssign = async () => {
        if (!selectedUser) return;
        setAssigning(true);

        try {
            await ApiUtils.assignUserToProject(project.id, {
                user_id: selectedUser,
            });
            toast('Utente assegnato con successo', 'success');
            setSelectedUser('');
            await loadAssignments();
            onSuccess();
        } catch (err) {
            toast('Errore nell\'assegnazione: ' + err.message, 'error');
        } finally {
            setAssigning(false);
        }
    };

    const handleRemove = (userId, userName) => {
        setConfirmRemove({ userId, userName });
    };

    const executeRemove = async () => {
        if (!confirmRemove) return;
        
        try {
            await ApiUtils.removeUserFromProject(project.id, confirmRemove.userId);
            toast('Utente rimosso dalla pratica', 'success');
            setConfirmRemove(null);
            await loadAssignments();
            onSuccess();
        } catch (err) {
            toast('Errore nella rimozione: ' + err.message, 'error');
            setConfirmRemove(null);
        }
    };

    const assignedUserIds = assignments.map(a => a.user_id);
    const availableUsers = users.filter(u => !assignedUserIds.includes(u.id));

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
                <div className="flex items-center justify-between p-6 border-b border-slate-200 sticky top-0 bg-white">
                    <div>
                        <h3 className="text-lg font-semibold text-slate-800">Gestisci Assegnazioni</h3>
                        <p className="text-sm text-slate-500 mt-1">{project.name}</p>
                    </div>
                    <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <div className="p-6 space-y-6">
                    {/* Add User Section */}
                    <div className="space-y-4">
                        <h4 className="text-sm font-semibold text-slate-700">Aggiungi Utente</h4>
                        
                        <div>
                            <select
                                value={selectedUser}
                                onChange={(e) => setSelectedUser(e.target.value)}
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            >
                                <option value="">Seleziona un utente...</option>
                                {availableUsers.map(u => (
                                    <option key={u.id} value={u.id}>
                                        {u.full_name} ({u.email})
                                    </option>
                                ))}
                            </select>
                        </div>

                        {selectedUser && (
                            <button
                                onClick={handleAssign}
                                disabled={assigning}
                                className="w-full px-4 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                            >
                                {assigning ? 'Assegnazione...' : 'Assegna Utente'}
                            </button>
                        )}
                    </div>

                    {/* Current Assignments */}
                    <div className="space-y-4" key={`assignments-${refreshKey}`}>
                        <h4 className="text-sm font-semibold text-slate-700">
                            Utenti Assegnati ({assignments.length})
                        </h4>
                        
                        {loading ? (
                            <div className="text-center py-4">
                                <Spinner size="md" />
                            </div>
                        ) : assignments.length === 0 ? (
                            <p className="text-sm text-slate-500 text-center py-4">
                                Nessun utente assegnato a questa pratica
                            </p>
                        ) : (
                            <div className="space-y-2">
                                {assignments.map(assignment => {
                                    const avatarUrl = assignment.user_avatar ? window.ApiUsers?.getAvatarUrl(assignment.user_avatar) : null;
                                    return (
                                        <div key={`${assignment.id}-${refreshKey}`} className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
                                            <div className="flex items-center gap-3">
                                                {avatarUrl ? (
                                                    <img
                                                        src={avatarUrl}
                                                        alt={assignment.user_name}
                                                        className="w-8 h-8 rounded-full object-cover"
                                                    />
                                                ) : (
                                                    <div className="w-8 h-8 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 text-xs font-semibold">
                                                        {assignment.user_name?.charAt(0).toUpperCase() || '?'}
                                                    </div>
                                                )}
                                                <div>
                                                    <div className="font-medium text-slate-800 text-sm">
                                                        {assignment.user_name || 'Utente'}
                                                    </div>
                                                    <div className="text-xs text-slate-500">{assignment.user_email}</div>
                                                </div>
                                            </div>
                                            <button
                                            onClick={() => handleRemove(assignment.user_id, assignment.user_name)}
                                            className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                            title="Rimuovi assegnazione"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                            </svg>
                                        </button>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                </div>

                <div className="p-6 border-t border-slate-200">
                    <button
                        onClick={onClose}
                        className="w-full px-4 py-2 border border-slate-200 text-slate-600 font-medium rounded-lg hover:bg-slate-50 transition-colors"
                    >
                        Chiudi
                    </button>
                </div>
            </div>

            {/* Confirmation Modal */}
            {confirmRemove && (
                <ConfirmationModal
                    title="Rimuovi Utente"
                    message={`Sei sicuro di voler rimuovere ${confirmRemove.userName || 'questo utente'} dalla pratica?`}
                    confirmText="Rimuovi"
                    variant="danger"
                    onConfirm={executeRemove}
                    onCancel={() => setConfirmRemove(null)}
                />
            )}
        </div>
    );
}

window.AssignUsersModal = AssignUsersModal;

