'use client'

import { Suspense, useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import {
  Menu, X, ChevronDown, Phone, Mail, Search, Home,
  Info, Building2, Award, Globe, UserCheck, Users,
  Calendar, Monitor, Settings, User, Briefcase,
  MapPin, HelpCircle, Plane, BookOpen, FileText,
  ArrowRight,
  type LucideIcon,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { CourseSearch } from '@/components/course-search'
import { NavigationProgress } from '@/components/navigation-progress'
import { navItems, siteConfig, siteImages, courseSubjects } from '@/lib/site-config'
import { cn } from '@/lib/utils'

const iconMap: Record<string, LucideIcon> = {
  Info, Building2, Award, Globe, UserCheck, Users,
  Calendar, Monitor, Settings, User, Briefcase,
  MapPin, HelpCircle, Plane, BookOpen, FileText, Home,
}

function isActivePath(pathname: string, href?: string) {
  if (!href || href === '#') return false
  if (href === '/') return pathname === '/'
  return pathname === href || pathname.startsWith(`${href}/`)
}

function HeaderContent() {
  const pathname = usePathname()
  const [isOpen, setIsOpen] = useState(false)
  const [expandedMenus, setExpandedMenus] = useState<Record<string, boolean>>({})
  const [scrolled, setScrolled] = useState(false)
  const [searchOpen, setSearchOpen] = useState(false)

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12)
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => window.removeEventListener('scroll', onScroll)
  }, [])

  useEffect(() => {
    setIsOpen(false)
    setSearchOpen(false)
  }, [pathname])

  const navLinkClass = (href?: string, hasSubmenu?: boolean) =>
    cn(
      'relative px-3.5 py-2 text-sm font-bold transition-all duration-200 flex items-center gap-1.5 rounded-lg',
      isActivePath(pathname, href)
        ? 'text-primary bg-primary/8'
        : 'text-foreground/85 hover:text-primary hover:bg-muted/70',
      hasSubmenu && 'pr-2.5'
    )

  return (
    <>
      <NavigationProgress />

      <header
        className={cn(
          'sticky top-0 z-50 transition-all duration-300',
          scrolled
            ? 'bg-white/97 backdrop-blur-lg shadow-[0_1px_0_rgba(0,0,0,0.06),0_4px_20px_rgba(0,0,0,0.04)]'
            : 'bg-white border-b border-border/50'
        )}
      >
        {/* Top utility bar */}
        <div className="hidden lg:block bg-gradient-to-r from-primary via-primary to-primary/95 text-primary-foreground text-xs border-b border-white/10">
          <div className="container-wide flex items-center justify-between py-2.5">
            <p className="text-primary-foreground/85 truncate max-w-[50%]">
              {siteConfig.address.city}, {siteConfig.address.country}
            </p>
            <div className="flex items-center gap-5">
              <a
                href={`tel:${siteConfig.phone.replace(/\s/g, '')}`}
                className="flex items-center gap-1.5 hover:text-accent transition-colors"
              >
                <Phone className="w-3.5 h-3.5" />
                {siteConfig.phone}
              </a>
              <span className="text-white/20">|</span>
              <a href={`mailto:${siteConfig.email}`} className="flex items-center gap-1.5 hover:text-accent transition-colors">
                <Mail className="w-3.5 h-3.5" />
                {siteConfig.email}
              </a>
            </div>
          </div>
        </div>

        {/* Main nav */}
        <nav className="container-wide h-[4.25rem] lg:h-[4.75rem] flex items-center justify-between gap-6">
          <Link href="/" className="flex items-center shrink-0 group">
            <Image
              src={siteImages.logo}
              alt={siteConfig.shortName}
              width={190}
              height={52}
              className="h-10 lg:h-12 w-auto transition-opacity group-hover:opacity-90"
              priority
            />
          </Link>

          {/* Desktop navigation */}
          <div className="hidden lg:flex items-center gap-0.5 flex-1 justify-center max-w-3xl mx-auto">
            {navItems.map((item) => (
              <div key={item.label} className="relative group">
                <Link href={item.href ?? '#'} className={navLinkClass(item.href, !!item.submenu)}>
                  {item.label === 'Home' && <Home className="w-3.5 h-3.5" />}
                  {item.label}
                  {item.submenu && (
                    <ChevronDown className="w-3.5 h-3.5 opacity-50 group-hover:rotate-180 transition-transform duration-300" />
                  )}
                  {isActivePath(pathname, item.href) && (
                    <span className="absolute bottom-0.5 left-3.5 right-3.5 h-0.5 bg-accent rounded-full" />
                  )}
                </Link>

                {item.submenu && (
                  <div className="absolute left-1/2 -translate-x-1/2 top-full pt-3 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50 pointer-events-none group-hover:pointer-events-auto">
                    <div
                      className={cn(
                        'bg-white border border-border/50 rounded-2xl shadow-[0_20px_50px_rgba(0,0,0,0.12)] overflow-hidden ring-1 ring-black/5',
                        item.megaMenu ? 'w-[660px]' : 'w-80'
                      )}
                    >
                      {item.megaMenu ? (
                        <div className="grid grid-cols-5">
                          <div className="col-span-3 p-5 border-r border-border/40">
                            <p className="text-[10px] font-bold uppercase tracking-[0.15em] text-muted-foreground mb-3 px-1">
                              Our Services
                            </p>
                            <div className="space-y-0.5">
                              {item.submenu.map((sub) => {
                                const Icon = sub.icon ? iconMap[sub.icon] : Briefcase
                                return (
                                  <Link
                                    key={sub.label}
                                    href={sub.href}
                                    className="flex items-start gap-3 px-3 py-2.5 rounded-xl hover:bg-primary/5 group/item transition-colors"
                                  >
                                    <div className="w-9 h-9 rounded-lg bg-primary/5 group-hover/item:bg-primary/10 flex items-center justify-center shrink-0">
                                      <Icon className="w-4 h-4 text-primary" />
                                    </div>
                                    <div>
                                      <p className="text-sm font-semibold text-foreground group-hover/item:text-primary">{sub.label}</p>
                                      {sub.description && (
                                        <p className="text-xs text-muted-foreground leading-snug mt-0.5">{sub.description}</p>
                                      )}
                                    </div>
                                  </Link>
                                )
                              })}
                            </div>
                          </div>
                          <div className="col-span-2 p-5 bg-muted/25">
                            <p className="text-[10px] font-bold uppercase tracking-[0.15em] text-muted-foreground mb-3">
                              Course Categories
                            </p>
                            <div className="space-y-0.5 max-h-64 overflow-y-auto">
                              {courseSubjects.slice(0, 8).map((s) => (
                                <Link
                                  key={s.slug}
                                  href={`/courses?category=${s.slug}`}
                                  className="block px-2 py-1.5 text-xs text-foreground/80 hover:text-primary hover:bg-white rounded-lg transition-colors"
                                >
                                  {s.name}
                                </Link>
                              ))}
                            </div>
                            <Link href="/courses" className="flex items-center gap-1 text-xs font-semibold text-primary mt-3 px-2 hover:text-accent">
                              All categories <ArrowRight className="w-3 h-3" />
                            </Link>
                          </div>
                        </div>
                      ) : (
                        <div className="p-2.5">
                          {item.submenu.map((sub) => {
                            const Icon = sub.icon ? iconMap[sub.icon] : Info
                            return (
                              <Link
                                key={sub.label}
                                href={sub.href}
                                className={cn(
                                  'flex items-start gap-3 px-3 py-2.5 rounded-xl transition-colors',
                                  isActivePath(pathname, sub.href)
                                    ? 'bg-primary/8 text-primary'
                                    : 'hover:bg-primary/5 group/item'
                                )}
                              >
                                <div className="w-9 h-9 rounded-lg bg-primary/5 flex items-center justify-center shrink-0">
                                  <Icon className="w-4 h-4 text-primary" />
                                </div>
                                <div>
                                  <p className="text-sm font-semibold text-foreground group-hover/item:text-primary">{sub.label}</p>
                                  {sub.description && (
                                    <p className="text-xs text-muted-foreground mt-0.5">{sub.description}</p>
                                  )}
                                </div>
                              </Link>
                            )
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Desktop actions */}
          <div className="hidden lg:flex items-center gap-2 shrink-0">
            {searchOpen ? (
              <div className="w-60 animate-in fade-in slide-in-from-right-2 duration-200">
                <CourseSearch variant="compact" />
              </div>
            ) : (
              <button
                onClick={() => setSearchOpen(true)}
                className="flex items-center gap-2 text-sm text-muted-foreground hover:text-primary px-3 py-2 rounded-lg hover:bg-muted/60 border border-transparent hover:border-border/60 transition-all"
                aria-label="Open search"
              >
                <Search className="w-4 h-4" />
                <span className="hidden xl:inline">Search</span>
              </button>
            )}
            <Link href="/contact">
              <Button size="sm" className="bg-primary hover:bg-primary/90 text-primary-foreground font-semibold h-10 px-6 shadow-sm">
                Get in Touch
              </Button>
            </Link>
          </div>

          {/* Mobile toggle */}
          <button
            className="lg:hidden p-2.5 -mr-1 rounded-xl hover:bg-muted/60 border border-border/50 transition-colors"
            onClick={() => setIsOpen(!isOpen)}
            aria-label="Toggle menu"
          >
            {isOpen ? <X size={22} /> : <Menu size={22} />}
          </button>
        </nav>

        {/* Mobile menu */}
        {isOpen && (
          <div className="lg:hidden border-t border-border/60 bg-white max-h-[85vh] overflow-y-auto shadow-lg">
            <div className="container-wide py-5 space-y-4">
              <CourseSearch variant="compact" />

              {navItems.map((item) => (
                <div key={item.label} className="border-b border-border/40 last:border-0 pb-1">
                  {item.submenu ? (
                    <>
                      <button
                        onClick={() => setExpandedMenus((p) => ({ ...p, [item.label]: !p[item.label] }))}
                        className={cn(
                          'w-full text-left py-3 px-2 font-bold flex items-center justify-between rounded-lg',
                          isActivePath(pathname, item.href) ? 'text-primary bg-primary/5' : 'text-foreground'
                        )}
                      >
                        <span className="flex items-center gap-2">
                          {item.label === 'Home' && <Home className="w-4 h-4" />}
                          {item.label}
                        </span>
                        <ChevronDown className={cn('w-4 h-4 transition-transform', expandedMenus[item.label] && 'rotate-180')} />
                      </button>
                      {expandedMenus[item.label] && (
                        <div className="pl-4 pb-2 space-y-0.5 border-l-2 border-primary/20 ml-2 mb-2">
                          {item.href && (
                            <Link
                              href={item.href}
                              className="block py-2 px-3 text-sm font-medium text-primary rounded-lg"
                              onClick={() => setIsOpen(false)}
                            >
                              Overview
                            </Link>
                          )}
                          {item.submenu.map((sub) => (
                            <Link
                              key={sub.label}
                              href={sub.href}
                              className={cn(
                                'block py-2 px-3 text-sm rounded-lg',
                                isActivePath(pathname, sub.href)
                                  ? 'text-primary bg-primary/5 font-medium'
                                  : 'text-muted-foreground hover:text-primary'
                              )}
                              onClick={() => setIsOpen(false)}
                            >
                              {sub.label}
                            </Link>
                          ))}
                        </div>
                      )}
                    </>
                  ) : (
                    <Link
                      href={item.href ?? '/'}
                      className={cn(
                        'flex items-center gap-2 py-3 px-2 font-bold rounded-lg',
                        isActivePath(pathname, item.href) ? 'text-primary bg-primary/5' : 'text-foreground hover:bg-muted/50'
                      )}
                      onClick={() => setIsOpen(false)}
                    >
                      {item.label === 'Home' && <Home className="w-4 h-4" />}
                      {item.label}
                    </Link>
                  )}
                </div>
              ))}

              <Link href="/contact" onClick={() => setIsOpen(false)}>
                <Button className="w-full bg-primary text-primary-foreground font-semibold h-11 mt-2">
                  Get in Touch
                </Button>
              </Link>
            </div>
          </div>
        )}
      </header>
    </>
  )
}

export function Header() {
  return (
    <Suspense fallback={null}>
      <HeaderContent />
    </Suspense>
  )
}
