'use client';
import { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '../lib/authContext';
import { useNotifications } from '../lib/notificationsContext';
import ProfileDropdown from './ProfileDropdown';

interface TopBarProps {
  title: string;
  breadcrumb?: string;
  onMenuClick?: () => void;
}

const alertTypeStyle: Record<string, { icon: string; color: string }> = {
  info: { icon: 'ri-information-line', color: 'text-blue-500' },
  warning: { icon: 'ri-alert-line', color: 'text-yellow-500' },
  success: { icon: 'ri-checkbox-circle-line', color: 'text-green-500' },
  error: { icon: 'ri-error-warning-line', color: 'text-red-500' },
};

function timeAgo(ts: string) {
  const diff = Date.now() - new Date(ts).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
}

export default function TopBar({ title, breadcrumb, onMenuClick }: TopBarProps) {
  const [showNotif, setShowNotif] = useState(false);
  const [showProfile, setShowProfile] = useState(false);
  const { user, logout } = useAuth();
  const { notifications, markRead, markAllRead, dismiss, unreadCount } = useNotifications();
  const router = useRouter();
  const pathname = usePathname();
  const employeePrefix = pathname?.startsWith('/hr') || pathname?.startsWith('/admin') ? '/hr' : '';
  const notifRef = useRef<HTMLDivElement>(null);
  const profileRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) setShowNotif(false);
      if (profileRef.current && !profileRef.current.contains(e.target as Node)) setShowProfile(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const handleLogout = () => {
    logout();
    router.replace('/login');
  };

  return (
    <header className="fixed top-0 left-0 lg:left-64 right-0 h-16 bg-white border-b border-gray-100 flex items-center px-4 lg:px-6 z-30 shadow-sm gap-3">
      {/* Hamburger - mobile only */}
      <button
        onClick={onMenuClick}
        className="lg:hidden w-9 h-9 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer transition-all flex-shrink-0"
        aria-label="Open menu"
      >
        <i className="ri-menu-line text-xl" style={{ color: '#b828a0' }}></i>
      </button>

      <div className="flex-1 min-w-0">
        <p className="text-xs text-gray-400 hidden sm:block truncate">{breadcrumb || 'Home'} / {title}</p>
        <h1 className="text-sm lg:text-base font-bold text-gray-800 truncate">{title}</h1>
      </div>

      <div className="flex items-center gap-2 lg:gap-3 flex-shrink-0">
        {/* Search - hidden on small screens */}
        <div className="relative hidden md:block">
          <input
            type="text"
            placeholder="Search employee records..."
            className="bg-gray-50 border border-gray-100 rounded-full px-4 py-2 text-sm w-44 lg:w-56 outline-none transition-all"
            onFocus={e => (e.target.style.borderColor = '#b828a0')}
            onBlur={e => (e.target.style.borderColor = '#f3f4f6')}
            onKeyDown={e => {
              if (e.key === 'Enter') {
                const val = (e.target as HTMLInputElement).value.trim();
                if (val) router.push(`${employeePrefix}/employees?search=${encodeURIComponent(val)}`);
                else router.push(`${employeePrefix}/employees`);
              }
            }}
          />
          <button
            className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2 cursor-pointer"
            onClick={e => {
              const input = (e.currentTarget.previousElementSibling as HTMLInputElement);
              const val = input?.value.trim();
              if (val) router.push(`${employeePrefix}/employees?search=${encodeURIComponent(val)}`);
              else router.push(`${employeePrefix}/employees`);
            }}
          >
            <i className="ri-search-line text-gray-400 text-sm"></i>
          </button>
        </div>

        <div className="relative" ref={notifRef}>
          <button
            onClick={() => { setShowNotif(!showNotif); setShowProfile(false); }}
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-gray-100 cursor-pointer relative transition-all"
          >
            <i className="ri-notification-3-line text-gray-600 text-xl"></i>
            {unreadCount > 0 && (
              <span className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full text-white text-xs flex items-center justify-center font-bold" style={{ background: '#b828a0' }}>{unreadCount > 9 ? '9+' : unreadCount}</span>
            )}
          </button>
          {showNotif && (
            <div className="absolute right-0 top-11 w-80 lg:w-96 bg-white rounded-2xl shadow-2xl border border-gray-100 z-50 overflow-hidden">
              <div className="p-4 border-b border-gray-100 flex items-center justify-between" style={{ background: 'linear-gradient(135deg, #b828a0 0%, #8a1e78 100%)' }}>
                <div className="flex items-center gap-2">
                  <span className="font-semibold text-white">Notifications</span>
                  {unreadCount > 0 && <span className="bg-white/30 text-white text-xs px-2 py-0.5 rounded-full font-bold">{unreadCount} new</span>}
                </div>
                <button onClick={markAllRead} className="text-xs text-pink-200 hover:text-white cursor-pointer whitespace-nowrap">Mark all read</button>
              </div>
              <div className="max-h-72 overflow-y-auto">
                {notifications.length === 0 && (
                  <div className="text-center py-8">
                    <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2"><i className="ri-checkbox-circle-line text-4xl text-green-400"></i></div>
                    <p className="text-sm text-gray-400">No notifications</p>
                  </div>
                )}
                {notifications.slice(0, 8).map(n => {
                  const s = alertTypeStyle[n.alertType];
                  return (
                    <div
                      key={n.id}
                      onClick={() => markRead(n.id)}
                      className={`flex items-start gap-3 p-3.5 border-b border-gray-50 cursor-pointer transition-colors hover:bg-gray-50 ${!n.read ? 'bg-pink-50/40' : ''}`}
                    >
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${n.read ? 'bg-gray-100' : 'bg-pink-100'}`}>
                        <i className={`${s.icon} ${n.read ? 'text-gray-400' : s.color} text-base`}></i>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between gap-2">
                          <p className={`text-sm ${n.read ? 'text-gray-600' : 'font-semibold text-gray-800'}`}>{n.title}</p>
                          <button onClick={(e) => { e.stopPropagation(); dismiss(n.id); }} className="w-4 h-4 flex items-center justify-center flex-shrink-0 text-gray-300 hover:text-gray-500">
                            <i className="ri-close-line text-xs"></i>
                          </button>
                        </div>
                        <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{n.message}</p>
                        <p className="text-xs text-gray-400 mt-1">{timeAgo(n.timestamp)}</p>
                      </div>
                      {!n.read && <div className="w-2 h-2 rounded-full mt-2 flex-shrink-0" style={{ background: '#b828a0' }}></div>}
                    </div>
                  );
                })}
              </div>
              <div className="p-3 border-t border-gray-100 text-center">
                <Link href="/analytics" onClick={() => setShowNotif(false)} className="text-xs font-semibold cursor-pointer" style={{ color: '#b828a0' }}>
                  View all in Analytics & Alerts →
                </Link>
              </div>
            </div>
          )}
        </div>

        <ProfileDropdown />
      </div>
    </header>
  );
}
