import { useState } from 'react';

// ── TYPES ──────────────────────────────────────────────
interface RoleSelectorProps {
    roles: string[];
    userName: string;
    onSelect: (role: string) => void;
}

// ── CONFIG DES RÔLES ───────────────────────────────────
const ROLE_CONFIG: Record<string, {
    label: string;
    sublabel: string;
    icon: string;
    gradient: string;
    accent: string;
    features: string[];
}> = {
    Collaborateur: {
        label: 'Collaborateur',
        sublabel: 'Soumettre & suivre mes notes',
        icon: '👤',
        gradient: 'linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)',
        accent: '#6366f1',
        features: ['Créer des notes de frais', 'Suivre mes remboursements', 'Consulter mon historique'],
    },
    Collaboratrice: {
        label: 'Collaboratrice',
        sublabel: 'Soumettre & suivre mes notes',
        icon: '👤',
        gradient: 'linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)',
        accent: '#6366f1',
        features: ['Créer des notes de frais', 'Suivre mes remboursements', 'Consulter mon historique'],
    },
    Validateur: {
        label: 'Validateur',
        sublabel: 'Gérer les demandes à valider',
        icon: '✅',
        gradient: 'linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%)',
        accent: '#0ea5e9',
        features: ['Valider / refuser des notes', 'Consulter les justificatifs', 'Historique de mes décisions'],
    },
    Validatrice: {
        label: 'Validatrice',
        sublabel: 'Gérer les demandes à valider',
        icon: '✅',
        gradient: 'linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%)',
        accent: '#0ea5e9',
        features: ['Valider / refuser des notes', 'Consulter les justificatifs', 'Historique de mes décisions'],
    },
    Finance: {
        label: 'Finance',
        sublabel: 'Paiements & administration',
        icon: '💼',
        gradient: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
        accent: '#10b981',
        features: ['Gestion des paiements', 'Export XML virements', 'Paramètres TVA & km', 'Synchronisation Entra ID'],
    },
    superUtilisateur: {
        label: 'Super Utilisateur',
        sublabel: 'Supervision globale — lecture seule',
        icon: '🛡️',
        gradient: 'linear-gradient(135deg, #7c3aed 0%, #4c1d95 100%)',
        accent: '#7c3aed',
        features: ['Voir toutes les notes de l\'organisation', 'Filtrer par collaborateur, statut, mois', 'Visualiser les montants globaux'],
    },
    VerificateurFinance: {
        label: 'Vérificateur Finance',
        sublabel: 'Contrôle & vérification des notes',
        icon: '🔍',
        gradient: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
        accent: '#f59e0b',
        features: [
            'Vérifier les justificatifs soumis',
            'Contrôler la conformité des notes',
            'Signaler les anomalies',
        ],
    },
    ValidateurFinance: {
        label: 'Validateur Finance',
        sublabel: 'Validation finale & paiements',
        icon: '💳',
        gradient: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
        accent: '#10b981',
        features: [
            'Valider les notes après vérification',
            'Autoriser les virements',
            'Export XML & reporting',
            'Suivi des remboursements',
        ],
    },
};

// Normalise un rôle vers sa clé de config
const normalizeRole = (role: string): string => {
    const map: Record<string, string> = {
        collaborateur: 'Collaborateur',
        collaboratrice: 'Collaboratrice',
        validateur: 'Validateur',
        validatrice: 'Validatrice',
        finance: 'Finance',
        verificateurfinance: 'VerificateurFinance',
    validateurfinance: 'ValidateurFinance',
    };
    return map[role.toLowerCase()] ?? role;
};

// ── COMPOSANT ──────────────────────────────────────────
const RoleSelector = ({ roles, userName, onSelect }: RoleSelectorProps) => {
    const [hovered, setHovered] = useState<string | null>(null);
    const [selected, setSelected] = useState<string | null>(null);

    const uniqueRoles = [...new Set(roles.map(normalizeRole))];
    const initials = userName.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2);

    const handleSelect = (role: string) => {
        setSelected(role);
        setTimeout(() => onSelect(role), 280);
    };

    return (
        <div style={{
            minHeight: '100vh',
            background: 'linear-gradient(160deg, #0f172a 0%, #1e1b4b 50%, #0f172a 100%)',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            fontFamily: '"DM Sans", "Segoe UI", system-ui, sans-serif',
            padding: '32px 16px',
            position: 'relative',
            overflow: 'hidden',
        }}>
            {/* Fond décoratif */}
            <div style={{
                position: 'absolute', inset: 0, zIndex: 0,
                background: 'radial-gradient(ellipse 60% 40% at 50% 0%, rgba(99,102,241,0.18) 0%, transparent 70%)',
                pointerEvents: 'none',
            }} />
            <div style={{
                position: 'absolute', bottom: 0, left: 0, right: 0,
                height: 320,
                background: 'radial-gradient(ellipse 60% 40% at 50% 100%, rgba(16,185,129,0.08) 0%, transparent 70%)',
                pointerEvents: 'none',
            }} />

            {/* Contenu */}
            <div style={{ position: 'relative', zIndex: 1, width: '100%', maxWidth: 680 }}>

                {/* En-tête */}
                <div style={{ textAlign: 'center', marginBottom: 48 }}>
                    <div style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        width: 56, height: 56,
                        background: 'rgba(99,102,241,0.2)',
                        border: '1px solid rgba(99,102,241,0.4)',
                        borderRadius: 16, marginBottom: 24, fontSize: 24,
                    }}>📋</div>

                    <div style={{
                        display: 'inline-flex', alignItems: 'center', gap: 10,
                        background: 'rgba(255,255,255,0.06)',
                        border: '1px solid rgba(255,255,255,0.12)',
                        borderRadius: 100, padding: '6px 16px 6px 10px',
                        marginBottom: 20,
                    }}>
                        <div style={{
                            width: 28, height: 28,
                            background: 'linear-gradient(135deg,#6366f1,#4f46e5)',
                            borderRadius: '50%',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            color: '#fff', fontSize: 11, fontWeight: 800,
                        }}>{initials}</div>
                        <span style={{ color: 'rgba(255,255,255,0.7)', fontSize: 13, fontWeight: 500 }}>
                            {userName}
                        </span>
                    </div>

                    <h1 style={{
                        color: '#fff', fontSize: 28, fontWeight: 800,
                        margin: '0 0 8px', letterSpacing: '-0.5px',
                    }}>
                        Choisir votre mode
                    </h1>
                    <p style={{ color: 'rgba(255,255,255,0.45)', fontSize: 14, margin: 0 }}>
                        Votre compte dispose de {uniqueRoles.length} profils — sélectionnez celui à activer
                    </p>
                </div>

                {/* Cartes de rôles */}
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: uniqueRoles.length === 2 ? '1fr 1fr' : uniqueRoles.length === 3 ? '1fr 1fr 1fr' : '1fr 1fr',
                    gap: 16,
                }}>
                    {uniqueRoles.map(role => {
                        const cfg = ROLE_CONFIG[role] ?? {
                            label: role, sublabel: '', icon: '🔑',
                            gradient: 'linear-gradient(135deg,#64748b,#475569)',
                            accent: '#64748b', features: [],
                        };
                        const isHovered = hovered === role;
                        const isSelected = selected === role;

                        return (
                            <button
                                key={role}
                                onClick={() => handleSelect(role)}
                                onMouseEnter={() => setHovered(role)}
                                onMouseLeave={() => setHovered(null)}
                                style={{
                                    background: isSelected
                                        ? cfg.gradient
                                        : isHovered
                                            ? 'rgba(255,255,255,0.09)'
                                            : 'rgba(255,255,255,0.05)',
                                    border: `1.5px solid ${isHovered || isSelected ? cfg.accent : 'rgba(255,255,255,0.1)'}`,
                                    borderRadius: 20,
                                    padding: '28px 24px',
                                    cursor: 'pointer',
                                    textAlign: 'left',
                                    transition: 'all 0.22s cubic-bezier(0.34,1.56,0.64,1)',
                                    transform: isSelected ? 'scale(1.03)' : isHovered ? 'translateY(-3px)' : 'none',
                                    boxShadow: isHovered || isSelected
                                        ? `0 20px 40px rgba(0,0,0,0.4), 0 0 0 1px ${cfg.accent}33`
                                        : '0 4px 16px rgba(0,0,0,0.2)',
                                    fontFamily: 'inherit',
                                    outline: 'none',
                                }}
                            >
                                {/* Icône + label */}
                                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 16 }}>
                                    <div style={{
                                        width: 44, height: 44, borderRadius: 12, flexShrink: 0,
                                        background: isSelected ? 'rgba(255,255,255,0.2)' : `${cfg.accent}22`,
                                        border: `1px solid ${isSelected ? 'rgba(255,255,255,0.3)' : cfg.accent + '44'}`,
                                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        fontSize: 20,
                                        transition: 'all 0.2s',
                                    }}>{cfg.icon}</div>
                                    <div>
                                        <div style={{
                                            color: '#fff', fontSize: 16, fontWeight: 700,
                                            marginBottom: 3, letterSpacing: '-0.2px',
                                        }}>{cfg.label}</div>
                                        <div style={{
                                            color: isSelected ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.4)',
                                            fontSize: 12, fontWeight: 500,
                                            transition: 'color 0.2s',
                                        }}>{cfg.sublabel}</div>
                                    </div>
                                </div>

                                {/* Features */}
                                <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                                    {cfg.features.map((f, i) => (
                                        <div key={i} style={{
                                            display: 'flex', alignItems: 'center', gap: 8,
                                        }}>
                                            <div style={{
                                                width: 5, height: 5, borderRadius: '50%',
                                                background: isSelected ? 'rgba(255,255,255,0.7)' : cfg.accent,
                                                flexShrink: 0,
                                                transition: 'background 0.2s',
                                            }} />
                                            <span style={{
                                                color: isSelected ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.35)',
                                                fontSize: 12, fontWeight: 400,
                                                transition: 'color 0.2s',
                                            }}>{f}</span>
                                        </div>
                                    ))}
                                </div>

                                {/* CTA */}
                                <div style={{
                                    marginTop: 20,
                                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                }}>
                                    <span style={{
                                        fontSize: 12, fontWeight: 700,
                                        color: isSelected ? '#fff' : cfg.accent,
                                        textTransform: 'uppercase', letterSpacing: '0.8px',
                                        transition: 'color 0.2s',
                                    }}>
                                        {isSelected ? 'Ouverture...' : 'Accéder →'}
                                    </span>
                                    {isSelected && (
                                        <div style={{
                                            width: 18, height: 18, borderRadius: '50%',
                                            border: '2px solid rgba(255,255,255,0.6)',
                                            borderTopColor: '#fff',
                                            animation: 'spin 0.6s linear infinite',
                                        }} />
                                    )}
                                </div>
                            </button>
                        );
                    })}
                </div>

                {/* Footer */}
                <p style={{
                    textAlign: 'center', color: 'rgba(255,255,255,0.2)',
                    fontSize: 11, marginTop: 32,
                }}>
                    Vous pourrez changer de mode à tout moment depuis l'interface
                </p>
            </div>

            <style>{`
                @keyframes spin { to { transform: rotate(360deg); } }
            `}</style>
        </div>
    );
};

export default RoleSelector;
export { ROLE_CONFIG, normalizeRole };
export type { RoleSelectorProps };