// EmailPreferencesSection - Gestione preferenze notifiche email
// Component for managing email notification preferences

function EmailPreferencesSection() {
    const toast = useToast();
    const [preferences, setPreferences] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [updating, setUpdating] = React.useState(null); // Track which preference is being updated
    const [bulkUpdating, setBulkUpdating] = React.useState(false);

    // Fetch preferences on mount
    React.useEffect(() => {
        fetchPreferences();
    }, []);

    const fetchPreferences = async () => {
        setLoading(true);
        try {
            const data = await ApiUtils.getEmailPreferences();
            setPreferences(data.preferences || []);
        } catch (error) {
            console.error('Error fetching email preferences:', error);
            toast('Errore nel caricamento delle preferenze email', 'error');
        } finally {
            setLoading(false);
        }
    };

    const handleToggle = async (notificationType, currentEnabled) => {
        setUpdating(notificationType);
        try {
            await ApiUtils.updateSingleEmailPreference(notificationType, !currentEnabled);
            setPreferences(prev =>
                prev.map(pref =>
                    pref.notification_type === notificationType
                        ? { ...pref, email_enabled: !currentEnabled }
                        : pref
                )
            );
            toast('Preferenza aggiornata', 'success');
        } catch (error) {
            console.error('Error updating preference:', error);
            toast('Errore nell\'aggiornamento della preferenza', 'error');
        } finally {
            setUpdating(null);
        }
    };

    const handleEnableAll = async () => {
        setBulkUpdating(true);
        try {
            await ApiUtils.enableAllEmailPreferences();
            setPreferences(prev => prev.map(pref => ({ ...pref, email_enabled: true })));
            toast('Tutte le notifiche email attivate', 'success');
        } catch (error) {
            console.error('Error enabling all preferences:', error);
            toast('Errore nell\'attivazione delle notifiche', 'error');
        } finally {
            setBulkUpdating(false);
        }
    };

    const handleDisableAll = async () => {
        setBulkUpdating(true);
        try {
            await ApiUtils.disableAllEmailPreferences();
            setPreferences(prev => prev.map(pref => ({ ...pref, email_enabled: false })));
            toast('Tutte le notifiche email disattivate', 'success');
        } catch (error) {
            console.error('Error disabling all preferences:', error);
            toast('Errore nella disattivazione delle notifiche', 'error');
        } finally {
            setBulkUpdating(false);
        }
    };

    // Count enabled preferences
    const enabledCount = preferences.filter(p => p.email_enabled).length;
    const allEnabled = enabledCount === preferences.length && preferences.length > 0;
    const allDisabled = enabledCount === 0;

    if (loading) {
        return (
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                <div className="flex items-center justify-center py-8">
                    <Spinner className="w-6 h-6 text-brand-500" />
                    <span className="ml-3 text-slate-500">Caricamento preferenze...</span>
                </div>
            </div>
        );
    }

    return (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
            <div className="flex items-center justify-between mb-6">
                <div>
                    <h3 className="text-lg font-semibold text-slate-800">Notifiche Email</h3>
                    <p className="text-sm text-slate-500 mt-1">
                        Gestisci quali notifiche ricevere via email
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    <span className="text-sm text-slate-500">
                        {enabledCount}/{preferences.length} attive
                    </span>
                </div>
            </div>

            {/* Bulk Actions */}
            <div className="flex gap-3 mb-6 pb-6 border-b border-slate-200">
                <button
                    onClick={handleEnableAll}
                    disabled={bulkUpdating || allEnabled}
                    className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-emerald-700 bg-emerald-50 rounded-lg hover:bg-emerald-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {bulkUpdating ? (
                        <Spinner className="w-4 h-4" />
                    ) : (
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                    )}
                    Attiva Tutte
                </button>
                <button
                    onClick={handleDisableAll}
                    disabled={bulkUpdating || allDisabled}
                    className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-slate-700 bg-slate-100 rounded-lg hover:bg-slate-200 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {bulkUpdating ? (
                        <Spinner className="w-4 h-4" />
                    ) : (
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    )}
                    Disattiva Tutte
                </button>
            </div>

            {/* Preferences List */}
            {preferences.length === 0 ? (
                <div className="text-center py-8 text-slate-500">
                    <svg className="w-12 h-12 mx-auto mb-3 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                    <p>Nessuna preferenza email disponibile</p>
                </div>
            ) : (
                <div className="space-y-1">
                    {preferences.map((pref) => (
                        <div
                            key={pref.notification_type}
                            className="flex items-center justify-between py-3 px-4 rounded-lg hover:bg-slate-50 transition-colors"
                        >
                            <div className="flex items-center gap-3">
                                <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
                                    pref.email_enabled ? 'bg-brand-100 text-brand-600' : 'bg-slate-100 text-slate-400'
                                }`}>
                                    {getNotificationIcon(pref.notification_type)}
                                </div>
                                <div>
                                    <p className="text-sm font-medium text-slate-700">
                                        {pref.display_name}
                                    </p>
                                    <p className="text-xs text-slate-400">
                                        {getNotificationDescription(pref.notification_type)}
                                    </p>
                                </div>
                            </div>
                            <button
                                onClick={() => handleToggle(pref.notification_type, pref.email_enabled)}
                                disabled={updating === pref.notification_type || bulkUpdating}
                                className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 disabled:opacity-50 ${
                                    pref.email_enabled ? 'bg-brand-500' : 'bg-slate-200'
                                }`}
                                role="switch"
                                aria-checked={pref.email_enabled}
                                aria-label={`Toggle ${pref.display_name}`}
                            >
                                {updating === pref.notification_type ? (
                                    <span className="absolute inset-0 flex items-center justify-center">
                                        <Spinner className="w-3 h-3 text-white" />
                                    </span>
                                ) : (
                                    <span
                                        className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                                            pref.email_enabled ? 'translate-x-5' : 'translate-x-0'
                                        }`}
                                    />
                                )}
                            </button>
                        </div>
                    ))}
                </div>
            )}

            {/* Info Note */}
            <div className="mt-6 pt-6 border-t border-slate-200">
                <div className="flex items-start gap-3 p-4 bg-blue-50 rounded-lg">
                    <svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div className="text-sm text-blue-700">
                        <p className="font-medium">Nota</p>
                        <p className="mt-1 text-blue-600">
                            Le notifiche in-app continueranno ad essere ricevute indipendentemente da queste impostazioni.
                            Queste preferenze controllano solo le notifiche via email.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    );
}

// Helper function to get notification icon based on type
function getNotificationIcon(type) {
    const icons = {
        project_created: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
        ),
        project_assigned: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
            </svg>
        ),
        project_status_changed: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
        ),
        step_status_changed: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
        ),
        project_due_soon: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        ),
        comment_added: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
        ),
        project_comment_added: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
            </svg>
        ),
        user_mentioned: (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
            </svg>
        ),
    };

    // Default icon for unknown types
    return icons[type] || (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
        </svg>
    );
}

// Helper function to get notification description based on type
function getNotificationDescription(type) {
    const descriptions = {
        project_created: 'Ricevi email quando viene creata una nuova pratica',
        project_assigned: 'Ricevi email quando ti viene assegnata una pratica',
        project_status_changed: 'Ricevi email quando cambia lo stato di una pratica',
        step_status_changed: 'Ricevi email quando cambia lo stato di un passaggio',
        project_due_soon: 'Ricevi email quando una pratica sta per scadere',
        comment_added: 'Ricevi email quando viene aggiunto un commento ad uno step',
        project_comment_added: 'Ricevi email quando viene aggiunto un commento alla pratica',
        user_mentioned: 'Ricevi email quando qualcuno ti menziona (@) in un commento o nota',
    };

    return descriptions[type] || 'Ricevi notifiche per questo tipo di evento';
}

// Export to global scope
window.EmailPreferencesSection = EmailPreferencesSection;
