// Profiles View Component
const { useState, useEffect } = React;

const ProfilesView = () => {
    const toast = useToast();
    const [profiles, setProfiles] = useState([]);
    const [showAdd, setShowAdd] = useState(false);
    const [selectedProfile, setSelectedProfile] = useState(null);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [confirmRemove, setConfirmRemove] = useState(null); // profileId

    useEffect(() => {
        const fetchProfiles = () => {
            fetch('/profiles').then(r => r.json()).then(data => {
                if (data.status === 'success') setProfiles(data.profiles || []);
            }).catch(console.error).finally(() => setLoading(false));
        };
        fetchProfiles();
        const interval = setInterval(fetchProfiles, 5000);
        return () => clearInterval(interval);
    }, []);

    const handleRefresh = async (id) => {
        try { 
            await fetch(`/profiles/${id}/refresh`, { method: 'POST' }); 
            toast('Aggiornamento in corso...', 'info');
        }
        catch (e) { toast('Errore aggiornamento', 'error'); }
    };

    const handleRefreshAll = async () => {
        setRefreshing(true);
        try {
            await fetch('/profiles/refresh-all', { method: 'POST' });
            toast('Tutti i profili aggiornati', 'success');
        } catch (e) { toast('Errore aggiornamento', 'error'); }
        finally { setRefreshing(false); }
    };

    const handleRemove = (id) => {
        setConfirmRemove(id);
    };

    const executeRemove = async () => {
        if (!confirmRemove) return;
        
        try {
            const r = await fetch(`/profiles/${confirmRemove}`, { method: 'DELETE' });
            if (r.ok) { 
                toast('Profilo rimosso', 'success'); 
                setProfiles(p => p.filter(x => x.id !== confirmRemove)); 
            }
            setConfirmRemove(null);
        } catch (e) { 
            toast('Errore rimozione', 'error'); 
            setConfirmRemove(null);
        }
    };


    return (
        <div className="p-8 space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h3 className="text-lg font-semibold text-slate-900">Profili Email Attivi</h3>
                    <p className="text-sm text-slate-500">Clicca su un profilo per vedere le email ricevute</p>
                </div>
                <div className="flex items-center gap-2">
                    {profiles.length > 0 && (
                        <Button variant="secondary" onClick={handleRefreshAll} disabled={refreshing}>
                            {refreshing ? <><Spinner className="w-4 h-4" /> Aggiornamento...</> : '🔄 Aggiorna Tutti'}
                        </Button>
                    )}
                    <Button variant="primary" onClick={() => setShowAdd(true)}>➕ Aggiungi Manuale</Button>
                </div>
            </div>

            {loading ? (
                <Card className="p-12 text-center"><Spinner className="w-8 h-8 mx-auto text-brand-500" /></Card>
            ) : profiles.length === 0 ? (
                <Card className="p-12 text-center">
                    <div className="text-4xl mb-3">📭</div>
                    <div className="font-medium text-slate-900">Nessun profilo email</div>
                    <p className="text-sm text-slate-500 mt-1">I profili appariranno automaticamente dopo la registrazione</p>
                    <Button variant="secondary" className="mt-4" onClick={() => setShowAdd(true)}>Aggiungi Manualmente</Button>
                </Card>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {profiles.map(profile => (
                        <EmailProfileCard
                            key={profile.id}
                            profile={profile}
                            onRefresh={handleRefresh}
                            onRemove={handleRemove}
                            onViewEmails={setSelectedProfile}
                        />
                    ))}
                </div>
            )}

            {showAdd && <AddProfileModal onClose={() => setShowAdd(false)} onAdded={() => { setShowAdd(false); }} />}
            {selectedProfile && <EmailListModal profile={selectedProfile} onClose={() => setSelectedProfile(null)} />}

            {/* Confirmation Modal */}
            {confirmRemove && (
                <ConfirmationModal
                    title="Rimuovi Profilo"
                    message="Sei sicuro di voler rimuovere questo profilo email?"
                    confirmText="Rimuovi"
                    variant="danger"
                    onConfirm={executeRemove}
                    onCancel={() => setConfirmRemove(null)}
                />
            )}
        </div>
    );
};

window.ProfilesView = ProfilesView;

