'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import Cookies from 'js-cookie';
import { useUI } from '@/components/ui-context';
import { useAuth } from '@/components/auth-context';
import { api } from '@/lib/api';
import { activityWsUrl, safeWebSocket } from '@/lib/ws';
import { toast } from 'react-toastify';
import type { User } from '@/types';

interface HeaderProps {
  title: string;
}

function displayName(user: User | null): string {
  if (!user) return 'User';
  if (user.full_name && user.full_name.trim()) return user.full_name.trim();
  const local = user.email.split('@')[0].replace(/[._-]+/g, ' ');
  return local.replace(/\b\w/g, (c) => c.toUpperCase());
}

const ROLE_LABEL: Record<string, string> = {
  ADMIN: 'Super Admin',
  RECRUITER: 'Recruiter',
  INTERVIEWER: 'Interviewer',
  CANDIDATE: 'Candidate',
};

export default function Header({ title }: HeaderProps) {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const { user } = useAuth();
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [notifOpen, setNotifOpen] = useState(false);
  const [popupNotification, setPopupNotification] = useState<any | null>(null);
  const notifRef = useRef<HTMLDivElement>(null);

  const { toggleSidebar } = useUI();
  const router = useRouter();

  useEffect(() => {
    setTheme(document.documentElement.classList.contains('dark') ? 'dark' : 'light');
  }, []);

  // Notifications loader & WebSocket subscription
  useEffect(() => {
    if (!user) return;
    
    const fetchNotifications = () => {
      api.get('/notifications/')
        .then((res: any) => {
          const data = res.data;
          setNotifications(Array.isArray(data) ? data : (data?.results || []));
        })
        .catch(() => {});
    };

    fetchNotifications();

    const ws = safeWebSocket(activityWsUrl());
    if (!ws) return;

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        // Dispatch a general event so components (like dashboards) can auto-refresh
        window.dispatchEvent(new CustomEvent('ws-event', { detail: data }));
        
        if (data.event && data.notification && data.notification.user_id === user.id) {
          const newNotif = data.notification;
          setNotifications((prev) => [newNotif, ...prev]);
          setPopupNotification(newNotif);
          window.dispatchEvent(new CustomEvent('notification-received', { detail: data }));
        }
      } catch (err) {
        console.error('WebSocket parse error:', err);
      }
    };

    return () => {
      ws.close();
    };
  }, [user]);

  const handleMarkRead = (id: number) => {
    api.patch(`/notifications/${id}/read/`, {})
      .then(() => {
        setNotifications((prev) =>
          prev.map((n) => (n.id === id ? { ...n, is_read: true } : n))
        );
      })
      .catch(() => {});
  };

  const handleMarkAllRead = () => {
    api.post('/notifications/mark-all-read/', {})
      .then(() => {
        setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
      })
      .catch(() => {});
  };

  const unreadCount = notifications.filter((n) => !n.is_read).length;

  // Close the dropdown on outside click
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenuOpen(false);
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) setNotifOpen(false);
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  const toggleTheme = () => {
    const dark = theme !== 'dark';
    document.documentElement.classList.toggle('dark', dark);
    localStorage.setItem('theme', dark ? 'dark' : 'light');
    setTheme(dark ? 'dark' : 'light');
  };

  const handleLogout = () => {
    Cookies.remove('access_token');
    Cookies.remove('refresh_token');
    router.push('/login');
  };

  const name = displayName(user);
  const initial = name.charAt(0).toUpperCase();
  const roleLabel = user ? (ROLE_LABEL[user.role] || user.role) : '';

  // ── Admin role switcher (impersonation) — swaps the whole ATS session ──
  const impersonating = typeof window !== 'undefined' && !!Cookies.get('admin_access_token');
  const isRealAdmin = user?.role === 'ADMIN' || impersonating;

  const switchToRole = async (role: string) => {
    if (!role || role === 'ADMIN') return;
    try {
      const res = (await api.post('/users/admin/impersonate/', { role })) as {
        data: { access: string; refresh: string; user: { email: string } }; message?: string;
      };
      if (!Cookies.get('admin_access_token')) {
        Cookies.set('admin_access_token', Cookies.get('access_token') || '');
        Cookies.set('admin_refresh_token', Cookies.get('refresh_token') || '');
      }
      Cookies.set('access_token', res.data.access);
      Cookies.set('refresh_token', res.data.refresh);
      toast.success(res.message || `Now viewing as ${res.data.user.email}`);
      window.location.reload();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not switch role');
    }
  };

  const returnToAdmin = () => {
    const access = Cookies.get('admin_access_token');
    const refresh = Cookies.get('admin_refresh_token');
    if (access) Cookies.set('access_token', access);
    if (refresh) Cookies.set('refresh_token', refresh);
    Cookies.remove('admin_access_token');
    Cookies.remove('admin_refresh_token');
    window.location.reload();
  };

  return (
    <>
    <header className="flex justify-between items-center h-[70px] px-4 sm:px-6 border-b border-vz-border bg-white dark:bg-slate-900 dark:border-slate-800 sticky top-0 z-30 shadow-sm">
      {/* Left: toggle + title */}
      <div className="flex items-center gap-3 min-w-0">
        <button
          onClick={toggleSidebar}
          className="p-2 rounded-none text-slate-500 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer shrink-0"
          title="Toggle sidebar" aria-label="Toggle sidebar"
        >
          <i className="fa-solid fa-bars text-lg"></i>
        </button>
        <h1 className="text-base sm:text-lg font-semibold tracking-tight text-[#495057] dark:text-white truncate">{title}</h1>
      </div>

      {/* Right: icons + profile */}
      <div className="flex items-center gap-1 sm:gap-2 shrink-0">
        {/* Admin role switcher — sits left of the notification icon */}
        {isRealAdmin && !impersonating && (
          <select
            value="ADMIN"
            onChange={(e) => switchToRole(e.target.value)}
            title="Preview another role's view of the whole ATS"
            className="hidden md:block bg-white dark:bg-slate-800 border border-vz-border dark:border-slate-700 rounded-none px-2.5 py-1.5 text-xs font-semibold text-slate-700 dark:text-white focus:outline-none cursor-pointer"
          >
            {[
              ['ADMIN', 'Admin Dashboard'],
              ['RECRUITER', 'Recruiter'],
              ['TA_MANAGER', 'TA Manager'],
              ['HIRING_MANAGER', 'Hiring Manager'],
              ['PROJECT_MANAGER', 'Project Manager'],
              ['INTERVIEWER', 'Interviewer'],
            ].map(([value, label]) => (
              <option key={value} value={value} className="bg-white text-slate-900 dark:bg-slate-900 dark:text-slate-100">
                {label}
              </option>
            ))}
          </select>
        )}
        {impersonating && (
          <button
            onClick={returnToAdmin}
            title="Return to your admin session"
            className="hidden md:inline-flex items-center gap-1.5 bg-amber-50 dark:bg-amber-950/40 border border-amber-300 dark:border-amber-800 text-amber-700 dark:text-amber-300 rounded-none px-2.5 py-1.5 text-xs font-bold transition cursor-pointer"
          >
            <i className="fa-solid fa-user-secret" /> Return to Admin
          </button>
        )}

        {/* Notifications Dropdown */}
        <div className="relative" ref={notifRef}>
          <button
            onClick={() => setNotifOpen((v) => !v)}
            className="relative p-2 rounded-none text-slate-500 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
            title="Notifications"
            aria-label="Notifications"
          >
            <i className="fa-regular fa-bell text-lg"></i>
            {unreadCount > 0 && (
              <span className="absolute top-1 right-1 px-1 py-0.5 rounded-full text-[8px] font-extrabold bg-[#f06548] text-white leading-none transform translate-x-1/3 -translate-y-1/3">
                {unreadCount}
              </span>
            )}
          </button>

          {notifOpen && (
            <div className="absolute right-0 mt-2 w-80 bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-lg py-2 z-50 animate-in fade-in slide-in-from-top-1 duration-150">
              <div className="px-4 py-2 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center">
                <span className="text-xs font-bold text-slate-800 dark:text-slate-200">Notifications ({unreadCount} unread)</span>
                {unreadCount > 0 && (
                  <button
                    onClick={handleMarkAllRead}
                    className="text-[10px] text-[#405189] dark:text-indigo-400 hover:underline font-semibold"
                  >
                    Mark all read
                  </button>
                )}
              </div>
              <div className="max-h-64 overflow-y-auto divide-y divide-slate-100 dark:divide-slate-800">
                {notifications.length === 0 ? (
                  <div className="px-4 py-6 text-center text-xs text-vz-muted">No notifications yet.</div>
                ) : (
                  notifications.map((n) => (
                    <div
                      key={n.id}
                      onClick={() => {
                        handleMarkRead(n.id);
                        if (n.metadata?.jd_id) {
                          router.push(`/jobs/${n.metadata.jd_id}`);
                        }
                        setNotifOpen(false);
                      }}
                      className={`px-4 py-2.5 text-left cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/50 transition ${
                        !n.is_read ? 'bg-slate-50/50 dark:bg-slate-800/20' : ''
                      }`}
                    >
                      <div className="flex justify-between items-start gap-1">
                        <p className={`text-xs ${!n.is_read ? 'font-bold text-slate-800 dark:text-slate-100' : 'text-slate-600 dark:text-slate-300'}`}>
                          {!n.is_read && n.type === 'jd_pending_approval' && (
                            <span className="text-[8px] px-1.5 py-0.5 mr-1.5 font-black uppercase tracking-wider bg-orange-500 text-white rounded-none align-middle">
                              NEW
                            </span>
                          )}
                          {n.title}
                        </p>
                        <span className="text-[9px] text-vz-muted shrink-0">
                          {new Date(n.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                      <p className="text-[10px] text-vz-muted mt-1 leading-normal">{n.message}</p>
                    </div>
                  ))
                )}
              </div>
            </div>
          )}
        </div>

        {/* Messages */}
        <button className="relative p-2 rounded-none text-slate-500 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer" title="Messages" aria-label="Messages">
          <i className="fa-regular fa-comment-dots text-lg"></i>
          <span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-[#3577f1] ring-2 ring-white dark:ring-slate-900"></span>
        </button>


        {/* Theme toggle */}
        <button
          onClick={toggleTheme}
          className="p-2 rounded-none text-slate-500 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
          title={`Switch to ${theme === 'dark' ? 'Light' : 'Dark'} Mode`}
        >
          <i className={`fa-solid ${theme === 'dark' ? 'fa-sun' : 'fa-moon'} text-lg`}></i>
        </button>

        {/* Profile dropdown */}
        <div className="relative" ref={menuRef}>
          <button
            onClick={() => setMenuOpen((v) => !v)}
            className="flex items-center gap-2.5 pl-2 pr-1 py-1 rounded-none hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
          >
            <div className="hidden sm:block text-right leading-tight">
              <p className="text-sm text-[#495057] dark:text-slate-200">
                Hello,<span className="font-semibold ml-1">{name}</span>
              </p>
              <p className="text-[11px] text-vz-muted">{roleLabel}</p>
            </div>
            <span className="w-9 h-9 rounded-full bg-[#405189] text-white flex items-center justify-center text-sm font-semibold shrink-0">
              {initial}
            </span>
            <i className={`fa-solid fa-chevron-down text-xs text-slate-400 transition-transform ${menuOpen ? 'rotate-180' : ''}`}></i>
          </button>

          {menuOpen && (
            <div className="absolute right-0 mt-2 w-52 bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-lg py-1.5 z-50 animate-in fade-in slide-in-from-top-1 duration-150">
              <div className="px-4 py-2 border-b border-slate-100 dark:border-slate-800 sm:hidden">
                <p className="text-sm font-semibold text-[#495057] dark:text-slate-200">{name}</p>
                <p className="text-[11px] text-vz-muted">{roleLabel}</p>
              </div>
              <button
                onClick={() => { setMenuOpen(false); router.push('/profile'); }}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer"
              >
                <i className="fa-regular fa-user text-[#405189] w-4"></i> Profile
              </button>
              <button
                onClick={() => { setMenuOpen(false); toast.info('Inbox is coming soon.'); }}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer"
              >
                <i className="fa-regular fa-envelope text-[#0ab39c] w-4"></i> Inbox
              </button>
              <div className="border-t border-slate-100 dark:border-slate-800 my-1"></div>
              <button
                onClick={() => { setMenuOpen(false); handleLogout(); }}
                className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-[#f06548] hover:bg-rose-50 dark:hover:bg-rose-950/30 transition cursor-pointer"
              >
                <i className="fa-solid fa-right-from-bracket w-4"></i> Logout
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
    
    {/* Slide-in Top-Right Popup Alert Notification */}
    {popupNotification && (
      <div className="fixed top-4 right-4 z-[9999] w-80 bg-white dark:bg-slate-900 border-2 border-[#405189] dark:border-slate-800 shadow-2xl p-4 flex flex-col gap-2 animate-in fade-in slide-in-from-top-4 duration-300">
        <div className="flex justify-between items-start">
          <div className="flex items-center gap-2 font-bold text-slate-800 dark:text-white text-sm">
            <span>📋</span>
            <span>{popupNotification.title}</span>
          </div>
          <button 
            onClick={() => {
              handleMarkRead(popupNotification.id);
              setPopupNotification(null);
            }}
            className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xs font-bold"
          >
            ✕
          </button>
        </div>
        <div className="text-xs text-slate-650 dark:text-slate-300 whitespace-pre-line leading-relaxed">
          {popupNotification.message}
        </div>
        <div className="text-[10px] text-vz-muted">
          Just now
        </div>
        <div className="flex gap-2 justify-end mt-1">
          <button
            onClick={() => {
              const jdId = popupNotification.metadata?.jd_id;
              handleMarkRead(popupNotification.id);
              setPopupNotification(null);
              if (jdId) router.push(`/jobs/${jdId}`);
            }}
            className="px-2.5 py-1 bg-[#405189] hover:bg-[#354575] text-white text-[10px] font-semibold transition"
          >
            View JD
          </button>
          <button
            onClick={() => {
              handleMarkRead(popupNotification.id);
              setPopupNotification(null);
            }}
            className="px-2.5 py-1 bg-slate-100 dark:bg-slate-800 hover:bg-slate-200 text-slate-700 dark:text-slate-200 text-[10px] font-semibold border border-vz-border dark:border-slate-800 transition"
          >
            Dismiss
          </button>
        </div>
      </div>
    )}
    </>
  );
}
