// CreateProjectModal - Modal for creating new projects

function CreateProjectModal({ users, referenti, onClose, onSuccess }) {
    // Get today's date in YYYY-MM-DD format
    const today = new Date().toISOString().split('T')[0];
    
    const [formData, setFormData] = React.useState({
        name: '',
        slug: '',
        description: '',
        start_date: today,
        due_date: '',
        priority: 'high',
        notes: '',
    });
    const [selectedUsers, setSelectedUsers] = React.useState([]);
    const [selectedReferenti, setSelectedReferenti] = React.useState([]);
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');

    const generateSlug = (name) => {
        return name
            .toLowerCase()
            .replace(/[^a-z0-9\s-]/g, '')
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .trim();
    };

    const handleNameChange = (e) => {
        const name = e.target.value;
        setFormData({
            ...formData,
            name,
            slug: generateSlug(name),
        });
    };

    const handleUserToggle = (userId) => {
        setSelectedUsers(prev => {
            const existing = prev.includes(userId);
            if (existing) {
                return prev.filter(id => id !== userId);
            } else {
                return [...prev, userId];
            }
        });
    };

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

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

        try {
            const data = { ...formData };
            // Clean up empty optional fields
            if (!data.description) delete data.description;
            if (!data.notes) delete data.notes;
            if (!data.due_date) delete data.due_date;

            // Create project
            const project = await ApiUtils.createProject(data);
            
            // Assign selected users
            for (const userId of selectedUsers) {
                try {
                    await ApiUtils.assignUserToProject(project.id, {
                        user_id: userId,
                    });
                } catch (assignErr) {
                    console.error('Failed to assign user:', assignErr);
                }
            }

            // Assign selected referenti to the project
            for (const referenteId of selectedReferenti) {
                try {
                    // Get the referente's current project_ids and add the new project
                    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 assign referente:', 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">Nuova 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={handleNameChange}
                                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>

                        <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="create-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>

                    {/* User Assignment Section */}
                    {users && users.length > 0 && (
                        <div className="border-t border-slate-200 pt-4 mt-4">
                            <label className="block text-sm font-medium text-slate-700 mb-2">
                                Assegna Utenti
                            </label>
                            <p className="text-xs text-slate-500 mb-3">
                                I permessi dell'utente sono definiti nel suo profilo
                            </p>
                            <div className="space-y-2 max-h-48 overflow-y-auto border border-slate-200 rounded-lg p-3">
                                {users.map(user => {
                                    const isSelected = selectedUsers.includes(user.id);
                                    return (
                                        <label 
                                            key={user.id} 
                                            className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${
                                                isSelected ? 'bg-brand-50 border border-brand-200' : 'hover:bg-slate-50 border border-transparent'
                                            }`}
                                        >
                                            <input
                                                type="checkbox"
                                                checked={isSelected}
                                                onChange={() => handleUserToggle(user.id)}
                                                className="w-4 h-4 text-brand-500 rounded focus:ring-brand-500"
                                            />
                                            <div className="flex-1 min-w-0">
                                                <div className="text-sm font-medium text-slate-800">{user.full_name}</div>
                                                <div className="text-xs text-slate-500 truncate">{user.email}</div>
                                            </div>
                                        </label>
                                    );
                                })}
                            </div>
                            {selectedUsers.length > 0 && (
                                <p className="text-xs text-slate-500 mt-2">
                                    {selectedUsers.length} utente/i selezionato/i
                                </p>
                            )}
                        </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 ? 'Creazione...' : 'Crea Pratica'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

window.CreateProjectModal = CreateProjectModal;

