'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import api from '@/lib/api';

type NavChild = { name: string; href: string };

type NavLink = {
  name: string;
  href: string;
  id: string;
  children?: NavChild[];
};

const ChevronIcon = ({ className = 'w-4 h-4' }: { className?: string }) => (
  <svg className={className} fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
  </svg>
);

const ArrowIcon = () => (
  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
  </svg>
);

/**
 * Modern navigation header with pill menu, mega dropdowns, and brand yellow active states.
 */
export const Header: React.FC = () => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [mobileExpanded, setMobileExpanded] = useState<string | null>(null);
  const [activeSection, setActiveSection] = useState('');
  const [thematicAreas, setThematicAreas] = useState<any[]>([]);
  const [loadingThematicAreas, setLoadingThematicAreas] = useState(true);
  const pathname = usePathname();

  useEffect(() => {
    const fetchThematicAreas = async () => {
      try {
        setLoadingThematicAreas(true);
        const response: any = await api.getThematicAreas();

        let areas: any[] = [];
        if (Array.isArray(response)) {
          areas = response;
        } else if (response && typeof response === 'object' && 'data' in response && Array.isArray(response.data)) {
          areas = response.data;
        }

        const activeAreas = areas
          .filter((area: any) => area.status === 'active')
          .sort((a: any, b: any) => (a.order || 0) - (b.order || 0));

        setThematicAreas(activeAreas);
      } catch (err: any) {
        console.error('Error fetching thematic areas for header:', err);
        setThematicAreas([]);
      } finally {
        setLoadingThematicAreas(false);
      }
    };

    fetchThematicAreas();
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 12);

      const sections = ['who-we-are', 'what-we-do', 'get-involved'];
      const current = sections.find((section) => {
        const element = document.getElementById(section);
        if (element) {
          const rect = element.getBoundingClientRect();
          return rect.top <= 120 && rect.bottom >= 120;
        }
        return false;
      });
      if (current) setActiveSection(current);
    };

    window.addEventListener('scroll', handleScroll);
    handleScroll();
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => {
    setIsMobileMenuOpen(false);
    setMobileExpanded(null);
  }, [pathname]);

  useEffect(() => {
    document.body.style.overflow = isMobileMenuOpen ? 'hidden' : '';
    return () => {
      document.body.style.overflow = '';
    };
  }, [isMobileMenuOpen]);

  const navLinks: NavLink[] = [
    {
      name: 'Who We Are',
      href: '/#who-we-are',
      id: 'who-we-are',
      children: [
        { name: 'About Us', href: '/about-us' },
        { name: 'Our Leadership', href: '/our-leadership' },
        { name: 'Message from the Director', href: '/message-from-director' },
        { name: 'Our Policies', href: '/policies' },
      ],
    },
    {
      name: 'What We Do',
      href: '/#what-we-do',
      id: 'what-we-do',
      children: loadingThematicAreas
        ? []
        : thematicAreas.map((area: any) => ({
            name: area.title || area.slug,
            href: `/programs/${area.slug || area.id}`,
          })),
    },
    {
      name: 'Donors',
      href: '/donors',
      id: 'donors',
      children: [
        { name: 'Our Donors', href: '/donors' },
        { name: 'Become a Donor', href: '/donors#become-donor' },
      ],
    },
    {
      name: 'Get Involved',
      href: '/#get-involved',
      id: 'get-involved',
      children: [
        { name: 'Procurement', href: '/procurement' },
        { name: 'Work with Us', href: '/careers' },
        { name: 'Volunteer', href: '/contact-us' },
      ],
    },
    {
      name: 'Latest',
      href: '/blog',
      id: 'latest',
      children: [
        { name: 'Blog', href: '/blog' },
        { name: 'Stories', href: '/blog?category=story' },
        { name: 'Reports', href: '/reports' },
      ],
    },
    {
      name: 'Contact',
      href: '/contact-us',
      id: 'contact',
      children: [
        { name: 'Contact Us', href: '/contact-us' },
        { name: 'CFRM', href: '/cfrm' },
      ],
    },
  ];

  const pathMatches = (prefixes: string[]) =>
    prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));

  const isActive = (link: NavLink) => {
    if (pathname === '/') {
      return activeSection === link.id;
    }

    const routeMap: Record<string, string[]> = {
      'who-we-are': ['/about-us', '/our-leadership', '/message-from-director', '/policies', '/our-history'],
      'what-we-do': ['/programs'],
      donors: ['/donors'],
      'get-involved': ['/procurement', '/careers'],
      latest: ['/blog', '/reports'],
      contact: ['/contact-us', '/cfrm'],
    };

    return pathMatches(routeMap[link.id] || []);
  };

  const dropdownWidth = (id: string) => {
    if (id === 'what-we-do') return 'w-[min(36rem,calc(100vw-2rem))]';
    if (id === 'who-we-are') return 'w-72';
    return 'w-60';
  };

  const renderDropdown = (link: NavLink) => {
    if (!link.children?.length && !(link.id === 'what-we-do' && loadingThematicAreas)) {
      return null;
    }

    return (
      <div
        className={`site-nav-dropdown absolute left-0 right-auto top-[calc(100%+0.5rem)] z-50 ${dropdownWidth(link.id)}`}
      >
        <div className="site-nav-dropdown-panel">
          <div className="site-nav-dropdown-header">{link.name}</div>
          <div className="p-1.5">
            {link.id === 'what-we-do' && loadingThematicAreas ? (
              <div className="px-4 py-3 text-sm text-neutral-500">Loading programs…</div>
            ) : link.id === 'what-we-do' ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-0.5 max-h-80 overflow-y-auto">
                {link.children?.map((child) => (
                  <Link key={child.href} href={child.href} className="site-nav-dropdown-link rounded-lg">
                    <ArrowIcon />
                    <span className="truncate">{child.name}</span>
                  </Link>
                ))}
              </div>
            ) : (
              link.children?.map((child) => (
                <Link key={child.href} href={child.href} className="site-nav-dropdown-link rounded-lg">
                  <ArrowIcon />
                  <span>{child.name}</span>
                </Link>
              ))
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <header
      className={`site-header fixed top-0 left-0 right-0 z-50 border-b border-secondary-300 bg-white/95 ${
        isScrolled ? 'site-header--scrolled' : ''
      }`}
    >
      {/* Brand accent strip */}
      <div className="h-1 bg-gradient-to-r from-primary-500 via-primary-400 to-primary-500" />

      <nav className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="flex h-[4.25rem] items-center justify-between gap-4">
          {/* Logo */}
          <Link href="/" className="flex shrink-0 items-center">
            <Image
              src="/logo/logo-png.png"
              alt="SSEOA Logo"
              width={160}
              height={52}
              className="h-12 w-auto object-contain sm:h-14"
              priority
              quality={100}
              unoptimized
            />
          </Link>

          {/* Desktop — pill navigation */}
          <div className="hidden lg:flex flex-1 items-center justify-center">
            <div className="site-nav-pill flex items-center">
              {navLinks.map((link) => (
                <div key={link.id} className="site-nav-item relative">
                  <a
                    href={link.href}
                    className={`site-nav-link ${isActive(link) ? 'site-nav-link--active' : ''}`}
                  >
                    {link.name}
                    {link.children && <ChevronIcon className="w-3.5 h-3.5 opacity-70" />}
                  </a>
                  {renderDropdown(link)}
                </div>
              ))}
            </div>
          </div>

          {/* Donate CTA */}
          <div className="hidden lg:block shrink-0">
            <Link href="/donate" className="site-nav-donate">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden>
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
                />
              </svg>
              Donate
            </Link>
          </div>

          {/* Mobile toggle */}
          <button
            type="button"
            className="lg:hidden inline-flex h-10 w-10 items-center justify-center rounded-full border border-secondary-300 bg-secondary-100 text-neutral-800 transition-colors hover:bg-primary-100"
            onClick={() => setIsMobileMenuOpen((open) => !open)}
            aria-label={isMobileMenuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={isMobileMenuOpen}
          >
            {isMobileMenuOpen ? (
              <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            ) : (
              <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            )}
          </button>
        </div>
      </nav>

      {/* Mobile menu */}
      {isMobileMenuOpen && (
        <>
          <button
            type="button"
            className="fixed inset-0 top-[4.25rem] z-40 bg-neutral-900/40 backdrop-blur-sm lg:hidden"
            aria-label="Close menu overlay"
            onClick={() => setIsMobileMenuOpen(false)}
          />
          <div className="site-mobile-nav fixed left-0 right-0 top-[calc(4.25rem+0.25rem)] z-50 mx-3 max-h-[calc(100vh-5.5rem)] overflow-y-auto rounded-2xl border border-secondary-300 bg-white shadow-2xl lg:hidden">
            <div className="p-3 space-y-1">
              {navLinks.map((link) => {
                const expanded = mobileExpanded === link.id;
                const active = isActive(link);

                return (
                  <div key={link.id} className="overflow-hidden rounded-xl border border-secondary-200">
                    <div className="flex items-stretch">
                      <a
                        href={link.href}
                        className={`flex-1 px-4 py-3 text-sm font-semibold transition-colors ${
                          active
                            ? 'bg-primary-500 text-neutral-900'
                            : 'bg-secondary-100 text-neutral-800 hover:bg-secondary-200'
                        }`}
                        onClick={() => !link.children?.length && setIsMobileMenuOpen(false)}
                      >
                        {link.name}
                      </a>
                      {link.children && link.children.length > 0 && (
                        <button
                          type="button"
                          className={`px-3 border-l border-secondary-200 transition-colors ${
                            active ? 'bg-primary-500 text-neutral-900' : 'bg-secondary-100 text-neutral-700'
                          }`}
                          onClick={() => setMobileExpanded(expanded ? null : link.id)}
                          aria-label={`Toggle ${link.name} submenu`}
                        >
                          <ChevronIcon className={`w-4 h-4 transition-transform ${expanded ? 'rotate-180' : ''}`} />
                        </button>
                      )}
                    </div>

                    {expanded && link.children && link.children.length > 0 && (
                      <div className="border-t border-secondary-200 bg-white p-2">
                        {link.id === 'what-we-do' && loadingThematicAreas ? (
                          <p className="px-3 py-2 text-sm text-neutral-500">Loading programs…</p>
                        ) : (
                          <div className={link.id === 'what-we-do' ? 'grid grid-cols-1 gap-0.5' : 'space-y-0.5'}>
                            {link.children.map((child) => (
                              <Link
                                key={child.href}
                                href={child.href}
                                className="flex items-center gap-2 rounded-lg px-3 py-2.5 text-sm text-neutral-700 hover:bg-primary-50 hover:text-neutral-900"
                                onClick={() => setIsMobileMenuOpen(false)}
                              >
                                <ArrowIcon />
                                {child.name}
                              </Link>
                            ))}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}

              <Link
                href="/donate"
                className="mt-2 flex w-full items-center justify-center gap-2 rounded-xl bg-navy-800 px-4 py-3.5 text-sm font-bold text-white shadow-lg"
                onClick={() => setIsMobileMenuOpen(false)}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
                  />
                </svg>
                Donate Now
              </Link>
            </div>
          </div>
        </>
      )}
    </header>
  );
};
