'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  Bell, LayoutDashboard, BookOpen, Dumbbell, Mic, PenTool, Users, Camera,
  LogOut, User, Settings, Gift, HelpCircle, FileText, ChevronRight, X,
  MessageCircle, Loader2,
} from 'lucide-react';
import { useAuth } from '@/lib/AuthContext';
import useAccountNotifications from '@/components/account/useAccountNotifications';
import CourseSwitcher from '@/components/account/CourseSwitcher';
import {
  notificationEmoji,
  notificationTypeConfig,
  openNotificationLink,
  relativeNotificationTime,
} from '@/components/account/notificationUi';

const NAV_ITEMS = [
  { id: 'dashboard', label: 'Dashboard', icon: LayoutDashboard, href: '/account' },
  { id: 'syllabus', label: 'Syllabus', icon: BookOpen, href: '/account/syllabus' },
  { id: 'practice', label: 'Practice', icon: Dumbbell, href: '/account/practice' },
  { id: 'accent', label: 'Accent Enhancer', icon: Mic, href: '/account/accent-enhancer' },
  { id: 'oral', label: 'Oral Drill', icon: PenTool, href: '/account/oral-drill' },
  { id: 'emma', label: 'Practice with Emma', icon: Users, href: '/account/practice-with-emma' },
  { id: 'photo', label: 'Photo Mode', icon: Camera, href: '/account/photo-mode' },
  { id: 'writing', label: 'Writing Analyser', icon: FileText, href: '/account/writing-analyser' },
  { id: 'speaking', label: 'Speech Analyser', icon: MessageCircle, href: '/account/speech-analyser' },
];

const MENU_ITEMS = [
  { icon: User, label: 'My Profile', action: 'profile' },
  { icon: Gift, label: 'Refer a Friend', action: 'refer' },
  { icon: Settings, label: 'Settings', action: 'settings' },
  { icon: HelpCircle, label: 'FAQ', href: '/faq' },
  { icon: FileText, label: 'Blog', href: '/blog' },
];

function AccountUserAvatar({ avatarUrl, initials, name, size = 'h-8 w-8', textSize = 'text-xs', radius = 'rounded-lg' }) {
  return (
    <div className={`flex ${size} items-center justify-center overflow-hidden ${radius} font-extrabold text-white shadow`} style={{ background: 'linear-gradient(135deg, #4A1429 0%, #8B2252 100%)' }}>
      {avatarUrl ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={avatarUrl} alt={`${name || 'Student'} profile`} className="h-full w-full object-cover" />
      ) : (
        <span className={textSize}>{initials}</span>
      )}
    </div>
  );
}

export default function StudentDashNav({
  activeTab,
  accountUser,
  courses = [],
  activeCourseId,
  courseSwitching = false,
  courseSwitchError = '',
  onCourseChange,
  onMenuAction,
}) {
  const router = useRouter();
  const auth = useAuth();
  const user = { ...(accountUser || {}), ...(auth?.user || {}) };
  const [menuOpen, setMenuOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const menuRef = useRef(null);
  const notifRef = useRef(null);
  const {
    notifications,
    unreadCount,
    loading: notificationsLoading,
    error: notificationsError,
    markOne,
    markAll,
  } = useAccountNotifications();

  useEffect(() => {
    const handleOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) setMenuOpen(false);
      if (notifRef.current && !notifRef.current.contains(event.target)) setNotifOpen(false);
    };
    document.addEventListener('mousedown', handleOutside);
    return () => document.removeEventListener('mousedown', handleOutside);
  }, []);

  const initials = user?.full_name
    ? user.full_name.split(' ').map((part) => part[0]).join('').toUpperCase().slice(0, 2)
    : 'CV';
  const avatarUrl = user?.avatar || user?.profile_photo || '';

  const openNotification = (notification) => {
    markOne(notification.id);
    setNotifOpen(false);
    openNotificationLink(router, notification.link);
  };

  return (
    <header className="sticky top-0 z-40 border-b border-gray-100 bg-white shadow-sm">
      <div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4 sm:px-6">
        <div className="flex flex-shrink-0 items-center gap-2.5">
          <div className="flex h-9 w-9 items-center justify-center rounded-xl text-sm font-extrabold text-white shadow-md" style={{ background: 'linear-gradient(135deg, #4A1429 0%, #8B2252 100%)' }}>CV</div>
          <div className="hidden leading-tight sm:block">
            <div className="text-sm font-extrabold tracking-tight text-[#2D0A18]">Cambridge</div>
            <div className="-mt-0.5 text-sm font-extrabold tracking-tight text-[#2D0A18]">Veritas</div>
          </div>
        </div>

        <CourseSwitcher
          courses={courses}
          value={activeCourseId}
          onChange={onCourseChange}
          disabled={courseSwitching}
          error={courseSwitchError}
        />

        <div className="flex items-center gap-2" ref={menuRef}>
          <div className="relative" ref={notifRef}>
            <button type="button" aria-label="Notifications" onClick={() => { setNotifOpen((value) => !value); setMenuOpen(false); }} className="relative rounded-xl p-2 transition-colors hover:bg-gray-100">
              <Bell className="h-5 w-5 text-gray-500" />
              {unreadCount > 0 && (
                <span className="absolute right-1 top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-[#4A1429] px-0.5 text-[9px] font-extrabold text-white ring-2 ring-white">{unreadCount > 99 ? '99+' : unreadCount}</span>
              )}
            </button>

            {notifOpen && (
              <div className="absolute right-0 top-11 z-50 w-[min(22rem,calc(100vw-2rem))] overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-2xl" style={{ boxShadow: '0 20px 60px rgba(0,0,0,0.12)' }}>
                <div className="flex items-center justify-between border-b border-gray-100 px-4 py-3" style={{ background: 'linear-gradient(135deg, #4A1429, #8B2252)' }}>
                  <div className="flex items-center gap-2">
                    <Bell className="h-4 w-4 text-white" />
                    <span className="text-sm font-extrabold text-white">Notifications</span>
                    {unreadCount > 0 && <span className="rounded-full bg-[#D4B038] px-1.5 py-0.5 text-[10px] font-bold text-[#2D0A18]">{unreadCount} new</span>}
                  </div>
                  <div className="flex items-center gap-2">
                    {unreadCount > 0 && <button type="button" onClick={markAll} className="text-[11px] font-semibold text-white/70 transition-colors hover:text-white">Mark all read</button>}
                    <button type="button" aria-label="Close notifications" onClick={() => setNotifOpen(false)} className="rounded-lg p-1 transition-colors hover:bg-white/20"><X className="h-3.5 w-3.5 text-white/80" /></button>
                  </div>
                </div>

                <div className="max-h-80 overflow-y-auto">
                  {notificationsLoading && notifications.length === 0 && (
                    <div className="flex items-center justify-center gap-2 px-4 py-10 text-xs font-semibold text-gray-400"><Loader2 className="h-4 w-4 animate-spin" /> Loading updates…</div>
                  )}
                  {!notificationsLoading && notificationsError && notifications.length === 0 && <div className="px-4 py-10 text-center text-xs font-semibold text-red-500">{notificationsError}</div>}
                  {!notificationsLoading && !notificationsError && notifications.length === 0 && <div className="px-4 py-10 text-center text-xs font-semibold text-gray-400">No notifications yet.</div>}
                  {notifications.slice(0, 6).map((notification) => {
                    const config = notificationTypeConfig(notification.type);
                    return (
                      <button type="button" key={notification.id} onClick={() => openNotification(notification)} className="flex w-full gap-3 border-b border-gray-50 px-4 py-3 text-left transition-colors hover:bg-gray-50" style={{ background: notification.read ? '#fff' : 'rgba(74,20,41,0.04)' }}>
                        <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl text-base" style={{ background: notification.read ? '#F3F4F6' : config.bg, boxShadow: notification.read ? 'none' : '0 2px 8px rgba(0,0,0,0.15)' }}>{notificationEmoji(notification.icon, config.emoji)}</div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center justify-between gap-1">
                            <p className="truncate text-xs font-bold text-[#2D0A18]">{notification.title}</p>
                            {!notification.read && <span className="h-2 w-2 flex-shrink-0 rounded-full bg-[#4A1429]" />}
                          </div>
                          <p className="mt-0.5 line-clamp-2 text-xs leading-relaxed text-gray-600">{notification.body}</p>
                          <p className="mt-1 text-[10px] font-medium text-gray-400">{relativeNotificationTime(notification.eventAt || notification.createdAt)}</p>
                        </div>
                      </button>
                    );
                  })}
                </div>

                <div className="border-t border-gray-100 px-4 py-2.5 text-center" style={{ background: 'linear-gradient(90deg, rgba(74,20,41,0.02), rgba(212,176,56,0.02))' }}>
                  <button type="button" onClick={() => { setNotifOpen(false); onMenuAction?.('notifications'); }} className="text-xs font-bold text-[#4A1429]">View all notifications →</button>
                </div>
              </div>
            )}
          </div>

          <button type="button" onClick={() => { setMenuOpen((value) => !value); setNotifOpen(false); }} className="flex items-center gap-2 rounded-xl border border-transparent py-1 pl-1 pr-2.5 transition-colors hover:border-gray-200 hover:bg-gray-50">
            <AccountUserAvatar avatarUrl={avatarUrl} initials={initials} name={user?.full_name} />
            <div className="hidden text-left sm:block">
              <div className="text-xs font-bold leading-none text-[#2D0A18]">{user?.full_name?.split(' ')[0] || 'Student'}</div>
              <div className="mt-0.5 text-[10px] leading-none text-gray-400">Student</div>
            </div>
          </button>

          {menuOpen && (
            <div className="absolute right-4 top-14 z-50 w-60 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-2xl sm:right-6" style={{ boxShadow: '0 20px 60px rgba(0,0,0,0.12)' }}>
              <div className="border-b border-gray-100 bg-gradient-to-r from-[#4A1429]/5 to-[#D4B038]/5 px-4 py-3.5">
                <div className="flex items-center gap-3">
                  <AccountUserAvatar avatarUrl={avatarUrl} initials={initials} name={user?.full_name} size="h-10 w-10" textSize="text-sm" radius="rounded-xl" />
                  <div className="min-w-0"><p className="truncate text-sm font-extrabold leading-tight text-[#2D0A18]">{user?.full_name || 'Student'}</p><p className="mt-0.5 max-w-[150px] truncate text-xs leading-tight text-gray-400">{user?.email || ''}</p></div>
                </div>
              </div>
              <div className="py-1.5">
                {MENU_ITEMS.map(({ icon: Icon, label, action, href }) => (
                  <button type="button" key={label} onClick={() => { setMenuOpen(false); if (href) router.push(href); else if (action) onMenuAction?.(action); }} className="group flex w-full items-center justify-between px-4 py-2.5 text-sm text-gray-700 transition-colors hover:bg-gray-50">
                    <div className="flex items-center gap-3"><div className="flex h-7 w-7 items-center justify-center rounded-lg bg-gray-100 transition-colors group-hover:bg-[#4A1429]/10"><Icon className="h-3.5 w-3.5 text-gray-500 group-hover:text-[#4A1429]" /></div><span className="font-medium">{label}</span></div><ChevronRight className="h-3.5 w-3.5 text-gray-300" />
                  </button>
                ))}
              </div>
              <div className="border-t border-gray-100 px-3 pb-3 pt-1"><button type="button" onClick={() => auth?.logout?.('/account/login')} className="flex w-full items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-bold text-white" style={{ background: 'linear-gradient(135deg, #4A1429, #8B2252)' }}><LogOut className="h-4 w-4" /> Sign Out</button></div>
            </div>
          )}
        </div>
      </div>

      <div className="scrollbar-hide mx-auto max-w-7xl overflow-x-auto px-4 sm:px-6">
        <div className="flex min-w-max items-end">
          {NAV_ITEMS.map(({ id, label, icon: Icon, href }) => (
            <Link href={href} key={id} className={`flex items-center gap-1.5 whitespace-nowrap border-b-2 px-4 py-3 text-xs font-semibold transition-all ${activeTab === id ? 'border-[#4A1429] text-[#4A1429]' : 'border-transparent text-gray-400 hover:border-gray-200 hover:text-gray-600'}`}>
              <Icon className="h-3.5 w-3.5 flex-shrink-0" />{label}
            </Link>
          ))}
        </div>
      </div>
    </header>
  );
}
