// EditProjectModal - Modal for editing project details (admin)

function EditProjectModal({ project, referenti, users, onClose, onSuccess }) {
    // Get today's date in YYYY-MM-DD format for fallback
    const today = new Date().toISOString().split('T')[0];

    const [formData, setFormData] = React.useState({
        name: project.name || '',
        description: project.description || '',
        start_date: project.start_date || today,
        due_date: project.due_date || '',
        priority: project.priority || 'medium',
        notes: project.notes || '',
    });

    // Initialize selected referenti based on those currently assigned to this project
    const [selectedReferenti, setSelectedReferenti] = React.useState(() => {
        if (!referenti) return [];
        return referenti
            .filter(r => r.project_ids && r.project_ids.includes(project.id))
            .map(r => r.id);
    });
    const [initialReferenti] = React.useState(() => {
        if (!referenti) return [];
        return referenti
            .filter(r => r.project_ids && r.project_ids.includes(project.id))
            .map(r => r.id);
    });

    // User assignments state
    const [assignments, setAssignments] = React.useState([]);
    const [initialAssignments, setInitialAssignments] = React.useState([]);
    const [loadingAssignments, setLoadingAssignments] = React.useState(true);

    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');

    // Load current assignments on mount
    React.useEffect(() => {
        const loadAssignments = async () => {
            setLoadingAssignments(true);
            try {
                const data = await ApiUtils.getProjectAssignments(project.id);
                const assignedUserIds = data.map(a => a.user_id);
                setAssignments(assignedUserIds);
                setInitialAssignments(assignedUserIds);
            } catch (err) {
                console.error('Failed to load assignments:', err);
            } finally {
                setLoadingAssignments(false);
            }
        };
        loadAssignments();
    }, [project.id]);

    const handleReferenteToggle = (referenteId) => {
        setSelectedReferenti(prev =>
            prev.includes(referenteId)
                ? prev.filter(id => id !== referenteId)
                : [...prev, referenteId]
        );
    };

    const handleUserToggle = (userId) => {
        setAssignments(prev =>
            prev.includes(userId)
                ? prev.filter(id => id !== userId)
                : [...prev, userId]
        );
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);

        try {
            // Convert empty strings to null for date fields
            const payload = {
                ...formData,
                start_date: formData.start_date || null,
                due_date: formData.due_date || null,
            };
            await ApiUtils.updateProject(project.id, payload);
            
            // Update referenti assignments
            const addedReferenti = selectedReferenti.filter(id => !initialReferenti.includes(id));
            const removedReferenti = initialReferenti.filter(id => !selectedReferenti.includes(id));
            
            // Add new referenti to the project
            for (const referenteId of addedReferenti) {
                try {
                    const referente = referenti.find(r => r.id === referenteId);
                    if (referente) {
                        const updatedProjectIds = [...(referente.project_ids || []), project.id];
                        await ApiUtils.updateReferente(referenteId, { project_ids: updatedProjectIds });
                    }
                } catch (assignErr) {
                    console.error('Failed to add referente:', assignErr);
                }
            }
            
            // Remove referenti from the project
            for (const referenteId of removedReferenti) {
                try {
                    const referente = referenti.find(r => r.id === referenteId);
                    if (referente) {
                        const updatedProjectIds = (referente.project_ids || []).filter(id => id !== project.id);
                        await ApiUtils.updateReferente(referenteId, { project_ids: updatedProjectIds });
                    }
                } catch (assignErr) {
                    console.error('Failed to remove referente:', assignErr);
                }
            }

            // Update user assignments
            const addedUsers = assignments.filter(id => !initialAssignments.includes(id));
            const removedUsers = initialAssignments.filter(id => !assignments.includes(id));

            // Add new users to the project
            for (const userId of addedUsers) {
                try {
                    await ApiUtils.assignUserToProject(project.id, { user_id: userId });
                } catch (assignErr) {
                    console.error('Failed to assign user:', assignErr);
                }
            }

            // Remove users from the project
            for (const userId of removedUsers) {
                try {
                    await ApiUtils.removeUserFromProject(project.id, userId);
                } catch (assignErr) {
                    console.error('Failed to remove user:', assignErr);
                }
            }

            onSuccess();
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    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">
                    <h3 className="text-lg font-semibold text-slate-800">Modifica Pratica</h3>
                    <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>

                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">Nome Pratica *</label>
                            <input
                                type="text"
                                value={formData.name}
                                onChange={(e) => setFormData({ ...formData, name: 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"
                                required
                            />
                        </div>

                        {/* Referenti Selection - inline in form */}
                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">
                                Referente
                                <span className="text-slate-400 font-normal ml-1">(persona di riferimento)</span>
                            </label>
                            {referenti && referenti.length > 0 ? (
                                <div className="space-y-2 max-h-32 overflow-y-auto border border-slate-200 rounded-lg p-2">
                                    {referenti.map(referente => {
                                        const isSelected = selectedReferenti.includes(referente.id);
                                        return (
                                            <label 
                                                key={referente.id} 
                                                className={`flex items-center gap-2 p-2 rounded-lg cursor-pointer transition-colors ${
                                                    isSelected ? 'bg-teal-50 border border-teal-200' : 'hover:bg-slate-50 border border-transparent'
                                                }`}
                                            >
                                                <input
                                                    type="checkbox"
                                                    checked={isSelected}
                                                    onChange={() => handleReferenteToggle(referente.id)}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div className="w-7 h-7 bg-gradient-to-br from-teal-400 to-teal-600 rounded-full flex items-center justify-center text-white font-semibold text-xs">
                                                    {referente.first_name?.charAt(0).toUpperCase()}{referente.last_name?.charAt(0).toUpperCase()}
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <span className="text-sm font-medium text-slate-800">{referente.full_name}</span>
                                                    {(referente.email || referente.phone_number) && (
                                                        <span className="text-xs text-slate-500 ml-2">
                                                            ({referente.email || referente.phone_number})
                                                        </span>
                                                    )}
                                                </div>
                                            </label>
                                        );
                                    })}
                                </div>
                            ) : (
                                <p className="text-sm text-slate-500 italic py-2">Nessun referente disponibile</p>
                            )}
                            {selectedReferenti.length > 0 && (
                                <p className="text-xs text-slate-500 mt-1">
                                    {selectedReferenti.length} referente/i selezionato/i
                                </p>
                            )}
                        </div>

                        {/* User Assignments Selection */}
                        {users && users.length > 0 && (
                            <div className="col-span-2">
                                <label className="block text-sm font-medium text-slate-700 mb-1">
                                    Utenti Assegnati
                                    <span className="text-slate-400 font-normal ml-1">(chi lavora sulla pratica)</span>
                                </label>
                                {loadingAssignments ? (
                                    <div className="flex items-center justify-center py-4 border border-slate-200 rounded-lg">
                                        <Spinner size="sm" />
                                        <span className="ml-2 text-sm text-slate-500">Caricamento...</span>
                                    </div>
                                ) : (
                                    <div className="space-y-2 max-h-32 overflow-y-auto border border-slate-200 rounded-lg p-2">
                                        {users.map(user => {
                                            const isSelected = assignments.includes(user.id);
                                            return (
                                                <label
                                                    key={user.id}
                                                    className={`flex items-center gap-2 p-2 rounded-lg cursor-pointer transition-colors ${
                                                        isSelected ? 'bg-blue-50 border border-blue-200' : 'hover:bg-slate-50 border border-transparent'
                                                    }`}
                                                >
                                                    <input
                                                        type="checkbox"
                                                        checked={isSelected}
                                                        onChange={() => handleUserToggle(user.id)}
                                                        className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                    />
                                                    <div className="w-7 h-7 bg-gradient-to-br from-blue-400 to-blue-600 rounded-full flex items-center justify-center text-white font-semibold text-xs">
                                                        {user.full_name?.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase() || '?'}
                                                    </div>
                                                    <div className="flex-1 min-w-0">
                                                        <span className="text-sm font-medium text-slate-800">{user.full_name}</span>
                                                        {user.email && (
                                                            <span className="text-xs text-slate-500 ml-2">
                                                                ({user.email})
                                                            </span>
                                                        )}
                                                    </div>
                                                </label>
                                            );
                                        })}
                                    </div>
                                )}
                                {assignments.length > 0 && (
                                    <p className="text-xs text-slate-500 mt-1">
                                        {assignments.length} utente/i assegnato/i
                                    </p>
                                )}
                            </div>
                        )}

                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">Data Inizio</label>
                            <input
                                type="date"
                                value={formData.start_date}
                                onChange={(e) => setFormData({ ...formData, start_date: 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"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-700 mb-1">Scadenza</label>
                            <input
                                type="date"
                                value={formData.due_date}
                                onChange={(e) => setFormData({ ...formData, due_date: 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"
                            />
                        </div>

                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">Priorità</label>
                            <div className="flex gap-4">
                                {['high', 'medium', 'low'].map(p => (
                                    <label key={p} className="flex items-center gap-2 cursor-pointer">
                                        <input
                                            type="radio"
                                            name="edit-priority"
                                            value={p}
                                            checked={formData.priority === p}
                                            onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                                            className="text-brand-500 focus:ring-brand-500"
                                        />
                                        <span className="text-sm text-slate-700">
                                            {p === 'high' ? 'Alta' : p === 'medium' ? 'Media' : 'Bassa'}
                                        </span>
                                    </label>
                                ))}
                            </div>
                        </div>

                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">Descrizione</label>
                            <textarea
                                value={formData.description}
                                onChange={(e) => setFormData({ ...formData, description: 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"
                                rows={2}
                            />
                        </div>

                        <div className="col-span-2">
                            <label className="block text-sm font-medium text-slate-700 mb-1">Note</label>
                            <textarea
                                value={formData.notes}
                                onChange={(e) => setFormData({ ...formData, notes: 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"
                                rows={2}
                            />
                        </div>
                    </div>

                    {error && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
                            {error}
                        </div>
                    )}

                    <div className="flex gap-3 pt-4">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 px-4 py-2 border border-slate-200 text-slate-600 font-medium rounded-lg hover:bg-slate-50 transition-colors"
                        >
                            Annulla
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-1 px-4 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                        >
                            {loading ? 'Salvataggio...' : 'Salva Modifiche'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

window.EditProjectModal = EditProjectModal;

