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

const Navbar = () => {
    const { user, logout, isSuperAdmin, isAdmin, isSupport, canViewLifecycle, isTechniker } = useAuth();
    const { notifications, unreadCount, markAllRead, markRead, addTestNotification } = useNotifications();
    const navigate = useNavigate();
    const isStaff = isSupport();
    const [showNotifDropdown, setShowNotifDropdown] = useState(false);
    const [showUserDropdown, setShowUserDropdown] = useState(false);
    const dropdownRef = useRef(null);
    const userDropdownRef = useRef(null);

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

    // Dropdown schließen bei Klick außerhalb
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setShowNotifDropdown(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleBellClick = () => {
        setShowNotifDropdown(prev => !prev);
    };

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

    const formatTime = (iso) => {
        const d = new Date(iso);
        const 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');
    };

    return (
        <nav className="navbar">
            <div className="navbar-container">
                <Link to={isStaff ? '/dashboard' : '/portal'} className="navbar-brand">
                    <Logo className="navbar-logo" width={150} height={45} />
                </Link>

                <ul className="navbar-menu">
                    {isStaff ? (
                        <>
                            <li><Link to="/dashboard" className="navbar-link">Dashboard</Link></li>
                            <li><Link to="/fido-keys" className="navbar-link">FIDO-Keys</Link></li>
                            <li><Link to="/assets" className="navbar-link">Assets</Link></li>
                            <li><Link to="/tickets" className="navbar-link">Tickets</Link></li>
                            <li><Link to="/knowledge-base" className="navbar-link">Wissensdatenbank</Link></li>
                            {['hr_personal', 'buchhaltung', 'support', 'admin', 'super_admin'].includes(user?.role_name) && (
                                <li><Link to="/lifecycle" className="navbar-link">Lifecycle</Link></li>
                            )}
                            {(isSuperAdmin() || isAdmin()) && (
                                <li><Link to="/it-overview" className="navbar-link">IT Übersicht</Link></li>
                            )}
                            {['admin', 'super_admin', 'buchhaltung'].includes(user?.role_name) && (
                                <li><Link to="/anlagevermoegen" className="navbar-link">Anlagevermögen</Link></li>
                            )}
                            {(isSuperAdmin() || isAdmin()) && (
                                <li><Link to="/users" className="navbar-link">Benutzer</Link></li>
                            )}
                        </>
                    ) : (
                        <>
                            <li><Link to="/portal" className="navbar-link">Mein Portal</Link></li>
                            {isTechniker() && (
                                <li><Link to="/assets" className="navbar-link">Assets</Link></li>
                            )}
                            {canViewLifecycle() && (
                                <li><Link to="/lifecycle" className="navbar-link">Lifecycle</Link></li>
                            )}
                        </>
                    )}
                </ul>

                <div className="user-menu">
                    {/* Benachrichtigungs-Glocke (nur für Staff) */}
                    {isStaff && (
                        <div ref={dropdownRef} style={{ position: 'relative' }}>
                            <button
                                onClick={handleBellClick}
                                title="Benachrichtigungen"
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    width: '34px',
                                    height: '34px',
                                    borderRadius: '8px',
                                    background: 'var(--bg-secondary)',
                                    border: '1px solid var(--border-color)',
                                    color: 'var(--text-secondary)',
                                    fontSize: '18px',
                                    cursor: 'pointer',
                                    transition: 'var(--transition)',
                                    flexShrink: 0,
                                    position: 'relative',
                                }}
                            >
                                🔔
                                {unreadCount > 0 && (
                                    <span style={{
                                        position: 'absolute',
                                        top: '-4px',
                                        right: '-4px',
                                        background: '#ef4444',
                                        color: '#fff',
                                        fontSize: '10px',
                                        fontWeight: 700,
                                        borderRadius: '10px',
                                        minWidth: '16px',
                                        height: '16px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        padding: '0 3px',
                                        lineHeight: 1,
                                    }}>
                                        {unreadCount > 9 ? '9+' : unreadCount}
                                    </span>
                                )}
                            </button>

                            {/* Dropdown */}
                            {showNotifDropdown && (
                                <div style={{
                                    position: 'absolute',
                                    top: 'calc(100% + 8px)',
                                    right: 0,
                                    width: '340px',
                                    background: 'var(--bg-card)',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '12px',
                                    boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
                                    zIndex: 1000,
                                    overflow: 'hidden',
                                }}>
                                    {/* Header */}
                                    <div style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        padding: '12px 16px',
                                        borderBottom: '1px solid var(--border-color)',
                                    }}>
                                        <span style={{ fontWeight: 700, fontSize: '14px', color: 'var(--text-primary)' }}>
                                            Benachrichtigungen
                                        </span>
                                        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                            <button
                                                onClick={addTestNotification}
                                                title="Test-Benachrichtigung senden"
                                                style={{
                                                    background: 'none',
                                                    border: '1px solid var(--border-color)',
                                                    borderRadius: '4px',
                                                    color: 'var(--text-muted)',
                                                    fontSize: '11px',
                                                    cursor: 'pointer',
                                                    padding: '2px 6px',
                                                }}
                                            >
                                                🧪 Test
                                            </button>
                                            {unreadCount > 0 && (
                                                <button
                                                    onClick={markAllRead}
                                                    style={{
                                                        background: 'none',
                                                        border: 'none',
                                                        color: 'var(--cereda-primary)',
                                                        fontSize: '12px',
                                                        cursor: 'pointer',
                                                        fontWeight: 600,
                                                        padding: 0,
                                                    }}
                                                >
                                                    Alle gelesen
                                                </button>
                                            )}
                                        </div>
                                    </div>

                                    {/* Liste */}
                                    <div style={{ maxHeight: '360px', overflowY: 'auto' }}>
                                        {notifications.length === 0 ? (
                                            <div style={{
                                                padding: '32px 16px',
                                                textAlign: 'center',
                                                color: 'var(--text-muted)',
                                                fontSize: '13px',
                                            }}>
                                                <div style={{ fontSize: '28px', marginBottom: '8px' }}>🔕</div>
                                                Keine Benachrichtigungen
                                            </div>
                                        ) : (
                                            notifications.map(notif => (
                                                <div
                                                    key={notif.id}
                                                    onClick={() => handleNotifClick(notif)}
                                                    style={{
                                                        display: 'flex',
                                                        gap: '12px',
                                                        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: '36px',
                                                        height: '36px',
                                                        borderRadius: '8px',
                                                        background: notif.critical ? 'rgba(239,68,68,0.12)' : 'rgba(59,130,246,0.12)',
                                                        display: 'flex',
                                                        alignItems: 'center',
                                                        justifyContent: 'center',
                                                        fontSize: '18px',
                                                        flexShrink: 0,
                                                    }}>
                                                        🎫
                                                    </div>
                                                    <div style={{ flex: 1, minWidth: 0 }}>
                                                        <div style={{
                                                            fontWeight: notif.read ? 500 : 700,
                                                            fontSize: '13px',
                                                            color: 'var(--text-primary)',
                                                            whiteSpace: 'nowrap',
                                                            overflow: 'hidden',
                                                            textOverflow: 'ellipsis',
                                                        }}>
                                                            {notif.title}
                                                        </div>
                                                        <div style={{
                                                            fontSize: '12px',
                                                            color: 'var(--text-secondary)',
                                                            marginTop: '2px',
                                                            whiteSpace: 'nowrap',
                                                            overflow: 'hidden',
                                                            textOverflow: 'ellipsis',
                                                        }}>
                                                            {notif.body}
                                                        </div>
                                                        <div style={{ fontSize: '11px', color: 'var(--text-muted)', marginTop: '4px' }}>
                                                            {formatTime(notif.createdAt)}
                                                        </div>
                                                    </div>
                                                    {!notif.read && (
                                                        <div style={{
                                                            width: '8px',
                                                            height: '8px',
                                                            borderRadius: '50%',
                                                            background: '#3b82f6',
                                                            flexShrink: 0,
                                                            alignSelf: 'center',
                                                        }} />
                                                    )}
                                                </div>
                                            ))
                                        )}
                                    </div>

                                    {/* Footer */}
                                    {notifications.length > 0 && (
                                        <div style={{
                                            padding: '10px 16px',
                                            borderTop: '1px solid var(--border-color)',
                                            textAlign: 'center',
                                        }}>
                                            <Link
                                                to="/tickets"
                                                onClick={() => setShowNotifDropdown(false)}
                                                style={{
                                                    fontSize: '12px',
                                                    color: 'var(--cereda-primary)',
                                                    textDecoration: 'none',
                                                    fontWeight: 600,
                                                }}
                                            >
                                                Alle Tickets ansehen →
                                            </Link>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    )}

                    {/* Zahnrad */}
                    {(isSuperAdmin() || isAdmin()) && (
                        <Link
                            to="/system"
                            className="navbar-gear-btn"
                            title="Systemeinstellungen"
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                width: '34px',
                                height: '34px',
                                borderRadius: '8px',
                                background: 'var(--bg-secondary)',
                                border: '1px solid var(--border-color)',
                                color: 'var(--text-secondary)',
                                fontSize: '18px',
                                textDecoration: 'none',
                                transition: 'var(--transition)',
                                flexShrink: 0,
                            }}
                        >
                            ⚙️
                        </Link>
                    )}

                    <div
                        ref={userDropdownRef}
                        style={{ position: 'relative' }}
                        onMouseEnter={() => setShowUserDropdown(true)}
                        onMouseLeave={() => setShowUserDropdown(false)}
                    >
                        <div className="user-info" style={{ cursor: 'pointer', userSelect: 'none' }}>
                            <span>{user?.username}</span>
                            <span className="role-badge">{user?.role_name}</span>
                        </div>

                        {showUserDropdown && (
                            <div style={{
                                position: 'absolute',
                                top: '100%',
                                right: 0,
                                minWidth: '180px',
                                background: 'var(--bg-card)',
                                border: '1px solid var(--border-color)',
                                borderRadius: '10px',
                                boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
                                zIndex: 1000,
                                overflow: 'hidden',
                                paddingTop: '4px',
                                paddingBottom: '4px',
                            }}>
                                <Link
                                    to="/mein-konto"
                                    onClick={() => setShowUserDropdown(false)}
                                    style={{
                                        display: 'flex', alignItems: 'center', gap: '10px',
                                        padding: '10px 16px', textDecoration: 'none',
                                        color: 'var(--text-primary)', fontSize: '14px', fontWeight: 500,
                                        transition: 'background 0.15s',
                                    }}
                                    onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-secondary)'}
                                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                >
                                    <span>👤</span> Mein Konto
                                </Link>
                                <div style={{ height: '1px', background: 'var(--border-color)', margin: '2px 0' }} />
                                <button
                                    onClick={handleLogout}
                                    style={{
                                        display: 'flex', alignItems: 'center', gap: '10px', width: '100%',
                                        padding: '10px 16px', background: 'none', border: 'none',
                                        color: '#ef4444', fontSize: '14px', fontWeight: 500,
                                        cursor: 'pointer', textAlign: 'left', transition: 'background 0.15s',
                                    }}
                                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(239,68,68,0.07)'}
                                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                >
                                    <span>🚪</span> Abmelden
                                </button>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </nav>
    );
};

export default Navbar;
