import { Bell, ChevronDown, Command, LogOut, Moon, Plus, Search, Settings, Sparkles, Sun, UserRound } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';
import { useTheme } from '../hooks/useTheme';

export default function Topbar() {
  const { user, logout } = useAuth();
  const { theme, setTheme } = useTheme();
  const navigate = useNavigate();
  const [profileOpen, setProfileOpen] = useState(false);
  const profileRef = useRef<HTMLDivElement>(null);

  const initials = user?.displayName
    ?.split(' ')
    .map(n => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2) || 'GA';

  useEffect(() => {
    const close = (event: MouseEvent) => {
      if (profileRef.current && !profileRef.current.contains(event.target as Node)) {
        setProfileOpen(false);
      }
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  return (
    <header className="topbar">
      <div className="global-search">
        <Search size={17} />
        <input aria-label="Search Kingdom BOS" placeholder="Search contacts, calls, clients, campaigns..." />
        <span className="search-shortcut"><Command size={12} /> K</span>
      </div>

      <div className="topbar-actions">
        <div className="theme-switcher" role="group" aria-label="Appearance">
          <button type="button" className={theme === 'light' ? 'active' : ''} onClick={() => setTheme('light')} aria-label="Use light theme" title="Light mode">
            <Sun size={14} /><span>Light</span>
          </button>
          <button type="button" className={theme === 'dark' ? 'active' : ''} onClick={() => setTheme('dark')} aria-label="Use dark theme" title="Dark mode">
            <Moon size={14} /><span>Dark</span>
          </button>
        </div>

        <button type="button" className="new-action" onClick={() => navigate('/clients/new')}>
          <Plus size={16} /> New
        </button>

        <button type="button" className="icon-button" aria-label="Notifications" title="Notifications" onClick={() => navigate('/alerts')}>
          <Bell size={18} />
          <span className="notification-dot" />
        </button>

        <button type="button" className="pulse-trigger" onClick={() => navigate('/analytics')} title="Open Business Pulse analytics">
          <span className="pulse-orb"><Sparkles size={15} /></span>
          <span>
            <small>Business Pulse</small>
            <strong>Healthy</strong>
          </span>
          <span className="health-dot" />
        </button>

        <div className="profile-menu-wrap" ref={profileRef}>
          <button type="button" className="profile-trigger" onClick={() => setProfileOpen(open => !open)} aria-expanded={profileOpen}>
            <span className="profile-avatar">{initials}</span>
            <span className="profile-copy">
              <strong>{user?.displayName || 'Admin'}</strong>
              <small>Super Admin</small>
            </span>
            <ChevronDown size={14} />
          </button>

          {profileOpen && (
            <div className="profile-menu" role="menu">
              <button type="button" onClick={() => { setProfileOpen(false); navigate('/settings'); }}>
                <UserRound size={15} /> Profile
              </button>
              <button type="button" onClick={() => { setProfileOpen(false); navigate('/settings'); }}>
                <Settings size={15} /> Settings
              </button>
              <div className="profile-menu-divider" />
              <button type="button" className="profile-menu-danger" onClick={() => logout()}>
                <LogOut size={15} /> Sign out
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
