'use client';

import { useState, useRef, useEffect } from 'react';
import { Icon } from '@iconify/react';
import { useAuth } from '@/context/AuthContext';
import { useSettings } from '@/context/SettingsContext';
import { NotificationPane } from './NotificationPane';
import { UserPane } from './UserPane';
import { SettingsDrawer } from './_components/SettingsDrawer';
import { HorizontalNav } from './HorizontalNav';
import Link from 'next/link';

export function Topbar() {
  const { user } = useAuth();
  const { navLayout, layout, themeMode } = useSettings();
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const notificationsRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);

  const initials = user
    ? `${user.firstName?.[0] ?? ''}${user.lastName?.[0] ?? ''}`.toUpperCase()
    : 'JF';

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (notificationsRef.current && !notificationsRef.current.contains(event.target as Node)) {
        setNotificationsOpen(false);
      }
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setUserMenuOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <>
      <div className="h-full flex items-center justify-between px-8">
        {/* Left side — Brand or Search */}
        <div className="flex items-center gap-4 h-full">
          {(navLayout === 'top') && (
            <Link href="/dashboard" className="flex items-center gap-3 mr-4 flex-shrink-0">
              <div className="flex items-center justify-center w-14 h-14 rounded-lg overflow-hidden">
                <img
                  src={themeMode === 'dark' ? '/uploads/config/logo_dark.png' : '/uploads/config/logo_light.png'}
                  alt="Logo"
                  className="w-full h-full object-contain"
                />
              </div>
              <span className="text-xl font-bold tracking-tight text-[var(--text-primary)]">
                Portal
              </span>
            </Link>
          )}

          {/* Placeholder for potential top-level search if Sidebar is vertical */}
          {navLayout !== 'top' && (
            <div className="flex items-center gap-2 group cursor-pointer">
              <Icon icon="solar:magnifer-linear" className="w-5 h-5 text-gray-400 group-hover:text-primary transition-colors" />
              <div className="hidden sm:flex items-center gap-1">
                <span className="text-sm font-medium text-gray-400">Search...</span>
                <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-md bg-gray-100 text-gray-400 border border-gray-200">⌘K</span>
              </div>
            </div>
          )}
        </div>

        {/* Right side — Actions */}
        <div className="flex items-center gap-2">
          {/* Language Switcher Placeholder */}
          <button className="p-2 rounded-xl hover:bg-gray-50 transition-all active:scale-95 grayscale hover:grayscale-0">
            <Icon icon="circle-flags:us" className="w-6 h-6" />
          </button>

          {/* Notifications */}
          <div className="relative" ref={notificationsRef}>
            <button
              onClick={() => setNotificationsOpen(!notificationsOpen)}
              className={`relative p-2.5 rounded-xl transition-all active:scale-95 group ${notificationsOpen ? 'bg-gray-100 text-gray-900' : 'text-gray-400 hover:bg-gray-50 hover:text-gray-900'
                }`}
            >
              <Icon icon="solar:bell-bing-bold-duotone" className={`w-6 h-6 transition-colors ${notificationsOpen ? 'text-primary' : ''}`} />
              <div className={`absolute top-1.5 right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-[#FF4842] text-white text-[10px] font-black border-2 border-white flex items-center justify-center transition-transform ${notificationsOpen ? 'scale-110' : ''}`}>
                4
              </div>
            </button>

            {notificationsOpen && <NotificationPane onClose={() => setNotificationsOpen(false)} />}
          </div>

          {/* Settings Toggle */}
          <button
            onClick={() => setSettingsOpen(true)}
            className="p-2.5 rounded-xl hover:bg-gray-50 text-gray-400 hover:text-gray-900 transition-all active:scale-95 group"
          >
            <Icon
              icon="solar:settings-bold-duotone"
              className="w-6 h-6 transition-transform duration-700 group-hover:rotate-180"
            />
          </button>

          {/* User Menu */}
          <div className="relative ml-2" ref={userMenuRef}>
            <button
              onClick={() => setUserMenuOpen(!userMenuOpen)}
              className={`p-1 rounded-full border-2 transition-all active:scale-95 ${userMenuOpen ? 'border-primary' : 'border-transparent hover:border-gray-200'
                }`}
            >
              <div className="w-9 h-9 rounded-full bg-[#C8FACD] text-[#007B55] font-black text-xs flex items-center justify-center shadow-sm overflow-hidden">
                {user?.photoUrl ? (
                  <img src={user.photoUrl} alt={initials} className="w-full h-full object-cover" />
                ) : (
                  initials
                )}
              </div>
            </button>

            {userMenuOpen && <UserPane onClose={() => setUserMenuOpen(false)} />}
          </div>
        </div>
      </div>
      {/* Slide-over Drawer - Moved outside header to avoid stacking context issues */}
      <SettingsDrawer isOpen={settingsOpen} onClose={() => setSettingsOpen(false)} />
    </>
  );
}
