import React, { useState, useRef, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import { useNotifications } from '../../context/NotificationContext';

const ROUTE_LABELS = {
    '/dashboard': 'Dashboard', '/portal': 'Mein Portal',
    '/tickets': 'Tickets', '/knowledge-base': 'Wissensdatenbank', '/anleitungen': 'Anleitungen',
    '/assets': 'Assets', '/warehouse': 'Lager', '/licenses': 'Lizenzen',
    '/maintenance': 'Wartung', '/fido-keys': 'FIDO-Keys', '/lifecycle': 'Lifecycle',
    '/anlagevermoegen': 'Anlagevermögen', '/monitoring': 'Monitoring',
    '/defender': 'Microsoft Defender', '/patch-management': 'Patch Management',
    '/it-overview': 'IT Übersicht', '/iso': 'ISO-Zertifizierung', '/risk': 'Risikoanalyse',
    '/entra': 'Entra Rechte', '/users': 'Benutzer', '/announcements': 'Ankündigungen',
    '/security-reports': 'Security Reports', '/ki-wissen': 'KI Wissensdatenbank',
    '/system': 'Systemeinstellungen', '/mein-konto': 'Mein Konto',
    '/onboarding': 'Onboarding', '/offboarding': 'Offboarding',
    '/proxmox': 'Proxmox', '/docker': 'Docker', '/health': 'Health',
};

const getPageLabel = (pathname) => {
    if (ROUTE_LABELS[pathname]) return ROUTE_LABELS[pathname];
    for (const [route, label] of Object.entries(ROUTE_LABELS)) {
        if (pathname.startsWith(route) && route !== '/') return label;
    }
    return pathname.replace('/', '').charAt(0).toUpperCase() + pathname.slice(2);
};

const formatTime = (iso) => {
    const d = new Date(iso), now = new Date();
    const diffMin = Math.floor((now - d) / 60000);
    if (diffMin < 1) return 'Gerade eben';
    if (diffMin < 60) return `vor ${diffMin} Min.`;
    const diffH = Math.floor(diffMin / 60);
    if (diffH < 24) return `vor ${diffH} Std.`;
    return d.toLocaleDateString('de-DE');
};

/* SVG Icons */
const BellIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M13.7 21a2 2 0 0 1-3.4 0"/>
    </svg>
);
const GearIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="3"/>
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
    </svg>
);
const SunIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
        <circle cx="12" cy="12" r="4"/>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
    </svg>
);
const MoonIcon = () => (
    <svg viewBox="0 0 24 24" fill="currentColor">
        <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>
    </svg>
);
const UserIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
    </svg>
);
const LogoutIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/>
    </svg>
);

/* ═══════════════════════════════════════════════════════════════════
   Topbar
═══════════════════════════════════════════════════════════════════ */
const Topbar = () => {
    const { user, logout, isSuperAdmin, isAdmin, isSupport } = useAuth();
    const { notifications, unreadCount, markAllRead, markRead, addTestNotification } = useNotifications();
    const navigate = useNavigate();
    const location = useLocation();
    const isStaff = isSupport();

    const [showNotif, setShowNotif] = useState(false);
    const [showUser, setShowUser] = useState(false);
    const [theme, setTheme] = useState(() => localStorage.getItem('nexus-theme') || 'dark');

    const notifRef = useRef(null);
    const userRef = useRef(null);

    const pageLabel = getPageLabel(location.pathname);
    const initials = (() => {
        const fn = user?.first_name?.[0] || '';
        const ln = user?.last_name?.[0] || '';
        return (fn + ln).toUpperCase() || (user?.username?.[0] || '?').toUpperCase();
    })();

    useEffect(() => {
        const saved = localStorage.getItem('nexus-theme') || 'dark';
        document.documentElement.setAttribute('data-theme', saved);
        setTheme(saved);
    }, []);

    const toggleTheme = () => {
        const next = theme === 'dark' ? 'light' : 'dark';
        setTheme(next);
        document.documentElement.setAttribute('data-theme', next);
        localStorage.setItem('nexus-theme', next);
    };

    useEffect(() => {
        const handler = (e) => {
            if (notifRef.current && !notifRef.current.contains(e.target)) setShowNotif(false);
            if (userRef.current && !userRef.current.contains(e.target)) setShowUser(false);
        };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    const handleLogout = async () => {
        await logout();
        navigate('/login');
    };

    const handleNotifClick = (notif) => {
        markRead(notif.id);
        setShowNotif(false);
        if (notif.ticketId) navigate(`/tickets/${notif.ticketId}`);
    };

    return (
        <header className="topbar">
            {/* Breadcrumb */}
            <div className="topbar-breadcrumb">
                <span>Cereda Systems</span>
                <span className="bc-sep">/</span>
                <span className="bc-current">{pageLabel}</span>
            </div>

            <div className="topbar-right">
                {/* Theme Toggle */}
                <button className="nx-theme-toggle" onClick={toggleTheme} aria-label="Theme umschalten">
                    <span className="tt-ico sun"><SunIcon /></span>
                    <span className="tt-ico moon"><MoonIcon /></span>
                    <span className="tt-thumb" />
                </button>

                {/* Notifications */}
                {isStaff && (
                    <div ref={notifRef} style={{ position: 'relative' }}>
                        <button className="topbar-icon-btn" onClick={() => setShowNotif(p => !p)} title="Benachrichtigungen" style={{ position: 'relative' }}>
                            <BellIcon />
                            {unreadCount > 0 && (
                                <span style={{
                                    position: 'absolute', top: '-3px', right: '-3px',
                                    background: '#ff3b30', color: '#fff',
                                    fontSize: '9px', fontWeight: 700,
                                    borderRadius: '10px', minWidth: '16px', height: '16px',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    padding: '0 3px', border: '2px solid var(--bg-primary)',
                                }}>
                                    {unreadCount > 9 ? '9+' : unreadCount}
                                </span>
                            )}
                        </button>

                        {showNotif && (
                            <div className="notif-dropdown">
                                <div className="notif-dropdown-header">
                                    <span style={{ fontWeight: 700, fontSize: 14 }}>Benachrichtigungen</span>
                                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                                        <button onClick={addTestNotification} title="Test" style={{ background: 'none', border: '1px solid var(--border-color)', borderRadius: 4, color: 'var(--text-muted)', fontSize: 11, cursor: 'pointer', padding: '2px 6px' }}>🧪</button>
                                        {unreadCount > 0 && <button onClick={markAllRead} style={{ background: 'none', border: 'none', color: 'var(--cereda-primary)', fontSize: 12, cursor: 'pointer', fontWeight: 600, padding: 0 }}>Alle gelesen</button>}
                                    </div>
                                </div>
                                <div style={{ maxHeight: 360, overflowY: 'auto' }}>
                                    {notifications.length === 0 ? (
                                        <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--text-muted)', fontSize: 13 }}>
                                            <div style={{ fontSize: 28, marginBottom: 8 }}>🔕</div>Keine Benachrichtigungen
                                        </div>
                                    ) : notifications.map(notif => (
                                        <div key={notif.id} onClick={() => handleNotifClick(notif)}
                                            style={{ display: 'flex', gap: 12, padding: '12px 16px', cursor: 'pointer', background: notif.read ? 'transparent' : 'rgba(59,130,246,0.06)', borderBottom: '1px solid var(--border-color)', transition: 'background 0.15s' }}
                                            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-secondary)'}
                                            onMouseLeave={e => e.currentTarget.style.background = notif.read ? 'transparent' : 'rgba(59,130,246,0.06)'}>
                                            <div style={{ width: 36, height: 36, borderRadius: 8, background: notif.critical ? 'rgba(239,68,68,0.12)' : 'rgba(59,130,246,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, flexShrink: 0 }}>🎫</div>
                                            <div style={{ flex: 1, minWidth: 0 }}>
                                                <div style={{ fontWeight: notif.read ? 500 : 700, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{notif.title}</div>
                                                <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{notif.body}</div>
                                                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>{formatTime(notif.createdAt)}</div>
                                            </div>
                                            {!notif.read && <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#3b82f6', flexShrink: 0, alignSelf: 'center' }} />}
                                        </div>
                                    ))}
                                </div>
                                {notifications.length > 0 && (
                                    <div style={{ padding: '10px 16px', borderTop: '1px solid var(--border-color)', textAlign: 'center' }}>
                                        <Link to="/tickets" onClick={() => setShowNotif(false)} style={{ fontSize: 12, color: 'var(--cereda-primary)', textDecoration: 'none', fontWeight: 600 }}>Alle Tickets →</Link>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                )}

                {/* Settings */}
                {(isSuperAdmin() || isAdmin()) && (
                    <Link to="/system" className="topbar-icon-btn" title="Systemeinstellungen" style={{ textDecoration: 'none' }}>
                        <GearIcon />
                    </Link>
                )}

                {/* User Chip */}
                <div ref={userRef} style={{ position: 'relative' }}>
                    <div className="nx-user-chip" onClick={() => setShowUser(p => !p)}>
                        <span className="nx-user-name">{user?.username}</span>
                        <span className="nx-user-role">{user?.role_name}</span>
                        <div className="nx-user-avatar">{initials}</div>
                    </div>

                    {showUser && (
                        <div className="nx-user-dropdown">
                            <Link to="/mein-konto" onClick={() => setShowUser(false)} className="nx-user-dropdown-item">
                                <UserIcon /> Mein Konto
                            </Link>
                            <div className="nx-user-dropdown-divider" />
                            <button onClick={handleLogout} className="nx-user-dropdown-item danger">
                                <LogoutIcon /> Abmelden
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </header>
    );
};

export default Topbar;
