import { useState } from 'react';
import { useAuth } from '../context/AuthContext';

// ── CONFIG ROLES (couleurs & icônes) ──────────────────
const ROLE_STYLE: Record<string, { icon: string; color: string; bg: string; label: string }> = {
    Collaborateur: { icon: '👤', color: '#a5b4fc', bg: 'rgba(99,102,241,0.2)', label: 'Collaborateur' },
    Collaboratrice: { icon: '👤', color: '#a5b4fc', bg: 'rgba(99,102,241,0.2)', label: 'Collaboratrice' },
    Validateur: { icon: '✅', color: '#7dd3fc', bg: 'rgba(14,165,233,0.2)', label: 'Validateur' },
    Validatrice: { icon: '✅', color: '#7dd3fc', bg: 'rgba(14,165,233,0.2)', label: 'Validatrice' },
    Finance: { icon: '💼', color: '#6ee7b7', bg: 'rgba(16,185,129,0.2)', label: 'Finance' },
    superUtilisateur: { icon: '🛡️', color: '#c4b5fd', bg: 'rgba(124,58,237,0.2)', label: 'Super Utilisateur' },
    VerificateurFinance: { icon: '🔍', color: '#c4b5fd', bg: 'rgba(124,58,237,0.2)', label: 'Vérificateur Finance' },
    ValidateurFinance: { icon: '💳', color: '#fca5a5', bg: 'rgba(185,28,28,0.2)', label: 'Validateur Finance' },
};

const getStyle = (role: string) =>
    ROLE_STYLE[role] ?? { icon: '🔑', color: '#cbd5e1', bg: 'rgba(100,116,139,0.2)', label: role };

// ══════════════════════════════════════════════════════
// VERSION SIDEBAR (intégrée dans la sidebar existante)
// ══════════════════════════════════════════════════════
export const RoleSwitcherSidebar = () => {
    const { activeRole, allRoles, switchRole, isMultiRole } = useAuth();
    const [open, setOpen] = useState(false);

    if (!isMultiRole || !activeRole) return null;

    const current = getStyle(activeRole);
    const others = allRoles.filter(r => r !== activeRole);

    return (
        <div style={{ padding: '0 10px', marginBottom: 4, position: 'relative' }}>
            {/* Bouton mode actif */}
            <button
                onClick={() => setOpen(!open)}
                style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 12px', borderRadius: 8, border: `1px solid ${current.color}44`,
                    background: current.bg, cursor: 'pointer',
                    fontFamily: 'inherit', fontSize: 12, textAlign: 'left',
                    transition: 'all 0.15s',
                }}
            >
                <span style={{ fontSize: 14 }}>{current.icon}</span>
                <div style={{ flex: 1, overflow: 'hidden' }}>
                    <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 9, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.6px' }}>Mode actif</div>
                    <div style={{ color: current.color, fontWeight: 700, fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {current.label}
                    </div>
                </div>
                <span style={{
                    color: 'rgba(255,255,255,0.4)', fontSize: 10,
                    transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
                    transition: 'transform 0.2s', display: 'inline-block',
                }}>▼</span>
            </button>

            {/* Dropdown des autres rôles */}
            {open && (
                <div style={{
                    position: 'absolute', left: 10, right: 10, top: '100%', marginTop: 4,
                    background: '#1e293b', border: '1px solid rgba(255,255,255,0.1)',
                    borderRadius: 10, overflow: 'hidden', zIndex: 300,
                    boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
                }}>
                    <div style={{ padding: '8px 12px 6px', fontSize: 10, fontWeight: 700, color: 'rgba(255,255,255,0.3)', textTransform: 'uppercase', letterSpacing: '0.6px' }}>
                        Changer de mode
                    </div>
                    {others.map(role => {
                        const s = getStyle(role);
                        return (
                            <button
                                key={role}
                                onClick={() => { switchRole(role); setOpen(false); }}
                                style={{
                                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                                    padding: '10px 12px', border: 'none', background: 'transparent',
                                    cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                                    transition: 'background 0.15s',
                                }}
                                onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.06)'; }}
                                onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent'; }}
                            >
                                <div style={{
                                    width: 30, height: 30, borderRadius: 8, background: s.bg,
                                    border: `1px solid ${s.color}44`,
                                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, flexShrink: 0,
                                }}>{s.icon}</div>
                                <div>
                                    <div style={{ color: '#fff', fontSize: 13, fontWeight: 600 }}>{s.label}</div>
                                    <div style={{ color: 'rgba(255,255,255,0.35)', fontSize: 10 }}>Basculer vers ce mode</div>
                                </div>
                                <span style={{ marginLeft: 'auto', color: s.color, fontSize: 11 }}>→</span>
                            </button>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ══════════════════════════════════════════════════════
// VERSION BADGE (dans le header, compact)
// ══════════════════════════════════════════════════════
export const RoleSwitcherBadge = () => {
    const { activeRole, allRoles, switchRole, isMultiRole } = useAuth();
    const [open, setOpen] = useState(false);

    if (!activeRole) return null;

    const current = getStyle(activeRole);
    const others = allRoles.filter(r => r !== activeRole);

    return (
        <div style={{ position: 'relative' }}>
            <button
                onClick={() => isMultiRole && setOpen(!open)}
                style={{
                    display: 'flex', alignItems: 'center', gap: 6,
                    padding: '6px 12px 6px 8px',
                    background: current.bg,
                    border: `1px solid ${current.color}55`,
                    borderRadius: 20, cursor: isMultiRole ? 'pointer' : 'default',
                    fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
                    color: current.color, transition: 'all 0.15s',
                }}
            >
                <span style={{ fontSize: 14 }}>{current.icon}</span>
                <span>{current.label}</span>
                {isMultiRole && (
                    <span style={{
                        fontSize: 8, opacity: 0.6,
                        transform: open ? 'rotate(180deg)' : 'none',
                        transition: 'transform 0.2s',
                    }}>▼</span>
                )}
            </button>

            {open && isMultiRole && (
                <>
                    {/* Overlay pour fermer */}
                    <div
                        style={{ position: 'fixed', inset: 0, zIndex: 199 }}
                        onClick={() => setOpen(false)}
                    />
                    <div style={{
                        position: 'absolute', right: 0, top: '100%', marginTop: 6,
                        minWidth: 200, background: '#fff',
                        border: '1px solid #e2e8f0', borderRadius: 12, overflow: 'hidden',
                        boxShadow: '0 8px 24px rgba(0,0,0,0.12)', zIndex: 200,
                    }}>
                        <div style={{ padding: '8px 12px 6px', fontSize: 10, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.6px', borderBottom: '1px solid #f1f5f9' }}>
                            Changer de mode
                        </div>
                        {others.map(role => {
                            const s = getStyle(role);
                            return (
                                <button
                                    key={role}
                                    onClick={() => { switchRole(role); setOpen(false); }}
                                    style={{
                                        width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                                        padding: '10px 14px', border: 'none', background: 'transparent',
                                        cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                                        transition: 'background 0.15s',
                                    }}
                                    onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = '#f8fafc'; }}
                                    onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent'; }}
                                >
                                    <div style={{
                                        width: 32, height: 32, borderRadius: 8,
                                        background: s.bg.replace('0.2', '0.15'),
                                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0,
                                    }}>{s.icon}</div>
                                    <div>
                                        <div style={{ fontSize: 13, fontWeight: 600, color: '#0f172a' }}>{s.label}</div>
                                        <div style={{ fontSize: 11, color: '#94a3b8' }}>Basculer vers ce mode</div>
                                    </div>
                                </button>
                            );
                        })}
                    </div>
                </>
            )}
        </div>
    );
};

// Export default = version sidebar (la plus courante)
export default RoleSwitcherSidebar;