'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import AuthModal from '@/components/AuthModal';
import { ArrowRight } from 'lucide-react';

interface NavbarProps {
  activePage?: 'home' | 'channel' | 'courses' | 'about' | 'contact';
}

export default function Navbar({ activePage }: NavbarProps) {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [authModalMode, setAuthModalMode] = useState<'login' | 'signup'>('signup');
  const [scrollProgress, setScrollProgress] = useState(0);
  const [activeSection, setActiveSection] = useState<string>('courses');

  const pathname = usePathname();
  const router = useRouter();
  const { user } = useAuth();

  const navItems = [
    { label: 'HOME', key: 'home', href: 'https://apkagermanschool.com/' },
    { label: 'CHANNEL', key: 'channel', href: '/channel' },
    { label: 'COURSES', key: 'courses', href: '/' },
    { label: 'ABOUT', key: 'about', href: '/about' },
    { label: 'CONTACT', key: 'contact', href: '/contact' },
  ];

  // Track window scroll progress percentage and active section
  useEffect(() => {
    const handleScroll = () => {
      const totalHeight = document.documentElement.scrollHeight - window.innerHeight;
      if (totalHeight > 0) {
        const progress = (window.scrollY / totalHeight) * 100;
        setScrollProgress(Math.min(100, Math.max(0, progress)));
      }

      if (pathname === '/') {
        const sections = ['courses', 'about', 'contact'];
        const scrollPosition = window.scrollY + 140;

        for (let i = sections.length - 1; i >= 0; i--) {
          const sectionId = sections[i];
          const el = document.getElementById(sectionId);
          if (el) {
            const top = el.offsetTop;
            if (scrollPosition >= top) {
              setActiveSection(sectionId);
              break;
            }
          }
        }
      }
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    handleScroll();
    return () => window.removeEventListener('scroll', handleScroll);
  }, [pathname]);

  const currentActive = activePage || (pathname === '/' ? activeSection : pathname?.replace('/', '') || 'courses');

  const handleNavClick = (sectionId: string, defaultHref: string, e: React.MouseEvent) => {
    setMobileMenuOpen(false);

    if (sectionId === 'home') {
      // Let the native Link handle the external navigation
      return;
    }

    if (sectionId === 'courses') {
      if (pathname === '/') {
        e.preventDefault();
        window.scrollTo({ top: 0, behavior: 'smooth' });
        setActiveSection('courses');
      }
      return;
    }

    if (pathname === '/') {
      e.preventDefault();
      setActiveSection(sectionId);

      const elem = document.getElementById(sectionId);
      if (elem) {
        const yOffset = 40;
        const y = elem.getBoundingClientRect().top + window.pageYOffset + yOffset;
        window.scrollTo({ top: y, behavior: 'smooth' });
      }
    }
  };

  return (
    <>
      {/* Absolute Floating Header Navbar with Top Scroll Progress Indicator */}
      <div className="absolute top-0 left-0 right-0 z-50 w-full bg-transparent transition-all duration-200 pointer-events-none">
        <div className="w-full px-4 sm:px-6 lg:px-8 py-4 sm:py-6 flex justify-center pointer-events-auto">
          <header
            className={`bg-white rounded-xl border border-gray-100 shadow-xl px-5 py-3.5 sm:py-4 w-full max-w-[1240px] mx-auto transition-all duration-200 ${mobileMenuOpen
              ? 'flex flex-col justify-start'
              : 'flex items-center justify-between min-h-[120px] sm:min-h-[120px]'
              }`}
          >
            {/* Top Header Row */}
            <div className="w-full flex items-center justify-between">
              {/* Brand B1 Logo Badge */}
              <Link
                href="/"
                onClick={(e) => handleNavClick('home', '/', e)}
                className="flex items-center gap-3 focus:outline-none group shrink-0"
              >
                <div className="relative w-[54px] h-[54px] sm:w-[77px] sm:h-[77px] rounded-xl bg-[#FBCC04] shadow-xs flex flex-col justify-between overflow-hidden transition-transform group-hover:scale-105">
                  <div className="flex-1 flex items-center justify-center pt-1">
                    <span className="text-black font-black text-2xl sm:text-5xl leading-none tracking-tight select-none">
                      B1
                    </span>
                  </div>

                  <div className="h-[5px] sm:h-[6px] w-full flex">
                    <div className="w-1/2 h-full bg-black"></div>
                    <div className="w-1/2 h-full bg-[#DC2626]"></div>
                  </div>
                </div>
              </Link>

              {/* Desktop Navigation Links */}
              <nav className="hidden md:flex items-center justify-center space-x-6 lg:space-x-8">
                {navItems.map((item) => {
                  const isActive = currentActive === item.key;
                  return (
                    <Link
                      key={item.key}
                      href={item.href}
                      onClick={(e) => handleNavClick(item.key, item.href, e)}
                      className={`font-sans text-sm sm:text-medium font-medium uppercase tracking-wide select-none transition-colors duration-150 cursor-pointer ${isActive
                        ? 'text-[#DC2626]'
                        : 'text-gray-900 hover:text-[#FBCC04]'
                        }`}
                    >
                      {item.label}
                    </Link>
                  );
                })}
              </nav>

              {/* Right Action Button & Auth State */}
              <div className="hidden md:flex items-center gap-4 shrink-0">
                {user && user.role !== 'admin' && user.role !== 'super_admin' ? (
                  <Link
                    href="/student/dashboard"
                    className="inline-flex items-center justify-center gap-2 px-8 py-3.5 rounded-xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] font-extrabold text-sm uppercase tracking-wider shadow-md hover:shadow-lg transition-all active:scale-95 group"
                  >
                    <span>DASHBOARD ({user.name})</span>
                    <ArrowRight className="w-4 h-4 text-black group-hover:text-[#FECE00] transition-colors" />
                  </Link>
                ) : (
                  <div
                    className="inline-flex items-center justify-center gap-2 px-8 py-3.5 rounded-xl bg-[#FECE00] text-black font-extrabold text-sm uppercase tracking-wider shadow-md cursor-default select-none"
                  >
                    <span>APPLY FOR COURSE</span>
                    <ArrowRight className="w-4 h-4 text-black" />
                  </div>
                )}
              </div>

              {/* Mobile Hamburger Toggle Button */}
              <div className="flex md:hidden items-center">
                <button
                  onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                  className="p-2 text-black hover:text-gray-700 focus:outline-none transition-colors"
                  aria-label={mobileMenuOpen ? 'Close navigation menu' : 'Open navigation menu'}
                >
                  {mobileMenuOpen ? (
                    <svg
                      className="w-6 h-6 text-black"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth={2.2}
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  ) : (
                    <svg
                      className="w-6 h-6 text-black"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth={2.2}
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" d="M4 7h16M4 12h16M4 17h16" />
                    </svg>
                  )}
                </button>
              </div>
            </div>

            {/* Mobile Expanded Menu */}
            {mobileMenuOpen && (
              <div className="md:hidden w-full pt-4 pb-3 flex flex-col items-start space-y-4 animate-fadeIn border-t border-gray-100 mt-3">
                {navItems.map((item) => {
                  const isActive = currentActive === item.key;
                  return (
                    <Link
                      key={item.key}
                      href={item.href}
                      onClick={(e) => handleNavClick(item.key, item.href, e)}
                      className={`font-sans text-sm tracking-wider uppercase transition-colors select-none ${isActive
                        ? 'text-[#DC2626]'
                        : 'text-gray-700 hover:text-black font-semibold'
                        }`}
                    >
                      {item.label}
                    </Link>
                  );
                })}
                {user && user.role !== 'admin' && user.role !== 'super_admin' ? (
                  <Link
                    href="/student/dashboard"
                    onClick={() => setMobileMenuOpen(false)}
                    className="w-full mt-2 py-3.5 px-4 rounded-xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] font-extrabold text-sm uppercase tracking-wider shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 cursor-pointer active:scale-95 group"
                  >
                    <span>DASHBOARD ({user.name})</span>
                    <ArrowRight className="w-4 h-4 text-black group-hover:text-[#FECE00] transition-colors" />
                  </Link>
                ) : (
                  <div
                    className="w-full mt-2 py-3.5 px-4 rounded-xl bg-[#FECE00] text-black font-extrabold text-sm uppercase tracking-wider shadow-md flex items-center justify-center gap-2 cursor-default select-none"
                  >
                    <span>APPLY FOR COURSE</span>
                    <ArrowRight className="w-4 h-4 text-black" />
                  </div>
                )}
              </div>
            )}
          </header>
        </div>
      </div>

      <AuthModal
        isOpen={authModalOpen}
        onClose={() => setAuthModalOpen(false)}
        initialMode={authModalMode}
      />
    </>
  );
}
