import React, { useState, useRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';

export default function Navbar() {
  const location = useLocation();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef(null);

  // Close dropdown if clicked outside
  useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setDropdownOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const coreLinks = [
    { name: 'Home', path: '/' },
    { name: 'About Us', path: '/about' },
    { name: 'Academics', path: '/academics' },
    { name: 'Admissions', path: '/admissions' },
    { name: 'News & Events', path: '/news' },
    { name: 'Contact', path: '/contact' }
  ];

  const moreLinks = [
    { name: 'Notice Board', path: '/notices', icon: 'campaign' },
    { name: 'Downloads & Docs', path: '/downloads', icon: 'download' },
    { name: 'Faculty Members', path: '/faculty', icon: 'groups' },
    { name: 'Photo Gallery', path: '/gallery', icon: 'photo_library' },
    { name: 'Achievements', path: '/achievements', icon: 'workspace_premium' },
    { name: 'Admin Console', path: '/admin', icon: 'admin_panel_settings' }
  ];

  const isActive = (path) => location.pathname === path;
  const isMoreActive = () => moreLinks.some(link => location.pathname === link.path);

  return (
    <nav className="fixed top-0 w-full z-50 bg-white/80 backdrop-blur-xl shadow-md border-b border-primary/10 transition-all duration-300">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16 items-center">
          
          {/* Logo & School Name */}
          <div className="flex items-center gap-2">
            <Link to="/" className="flex items-center gap-2">
              <span className="material-symbols-outlined text-[32px] text-primary" style={{ fontVariationSettings: "'FILL' 1" }}>school</span>
              <span className="font-headline font-bold text-xl md:text-2xl text-primary tracking-tight">St. Andrews</span>
            </Link>
          </div>

          {/* Desktop Navigation Links */}
          <div className="hidden lg:flex gap-6 items-center">
            {coreLinks.map((link) => (
              <Link
                key={link.path}
                to={link.path}
                className={`font-semibold text-sm transition-all pb-1 border-b-2 ${
                  isActive(link.path)
                    ? 'text-primary border-primary font-bold'
                    : 'text-on-surface-variant border-transparent hover:text-primary hover:border-primary/50'
                }`}
              >
                {link.name}
              </Link>
            ))}

            {/* "More" Dropdown Trigger */}
            <div className="relative" ref={dropdownRef}>
              <button
                onClick={() => setDropdownOpen(!dropdownOpen)}
                className={`flex items-center gap-1 font-semibold text-sm transition-all pb-1 border-b-2 focus:outline-none ${
                  isMoreActive()
                    ? 'text-primary border-primary font-bold'
                    : 'text-on-surface-variant border-transparent hover:text-primary'
                }`}
              >
                Explore
                <span className={`material-symbols-outlined text-base transition-transform duration-200 ${dropdownOpen ? 'rotate-180' : ''}`}>
                  expand_more
                </span>
              </button>

              {/* Dropdown Menu */}
              {dropdownOpen && (
                <div className="absolute right-0 mt-3 w-56 bg-white border border-primary/10 shadow-xl rounded-xl py-2 z-50 animate-fade-in">
                  {moreLinks.map((link) => (
                    <Link
                      key={link.path}
                      to={link.path}
                      onClick={() => setDropdownOpen(false)}
                      className={`flex items-center gap-3 px-4 py-2.5 text-sm transition-all ${
                        isActive(link.path)
                          ? 'bg-primary/5 text-primary font-bold border-l-4 border-primary'
                          : 'text-on-surface-variant hover:bg-surface-container hover:text-primary'
                      }`}
                    >
                      <span className="material-symbols-outlined text-lg text-primary">{link.icon}</span>
                      {link.name}
                    </Link>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Apply Now CTA */}
          <div className="hidden md:flex items-center gap-4">
            <Link to="/admissions">
              <button className="bg-primary text-on-primary px-6 py-2.5 rounded-full text-sm font-semibold hover:scale-105 active:scale-95 transition-all duration-200 shadow-md hover:shadow-primary/20">
                Apply Now
              </button>
            </Link>
          </div>

          {/* Mobile Menu Button */}
          <div className="flex items-center lg:hidden">
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="text-on-surface-variant hover:text-primary p-2 rounded-md focus:outline-none"
            >
              <span className="material-symbols-outlined text-2xl">
                {mobileMenuOpen ? 'close' : 'menu'}
              </span>
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Menu Panel */}
      {mobileMenuOpen && (
        <div className="lg:hidden bg-white/95 border-b border-primary/10 shadow-lg px-4 pt-2 pb-4 space-y-1 max-h-[80vh] overflow-y-auto">
          {/* Core Links */}
          <div className="border-b border-gray-100 pb-2 mb-2">
            <p className="px-4 py-1 text-xs font-bold text-gray-400 uppercase">Main Sections</p>
            {coreLinks.map((link) => (
              <Link
                key={link.path}
                to={link.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`block px-4 py-2 rounded-md text-base font-semibold transition-all ${
                  isActive(link.path)
                    ? 'bg-primary/10 text-primary font-bold'
                    : 'text-on-surface-variant hover:bg-surface-container hover:text-primary'
                }`}
              >
                {link.name}
              </Link>
            ))}
          </div>

          {/* More Links */}
          <div>
            <p className="px-4 py-1 text-xs font-bold text-gray-400 uppercase">Resources & Portal</p>
            {moreLinks.map((link) => (
              <Link
                key={link.path}
                to={link.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center gap-3 px-4 py-2 rounded-md text-base font-semibold transition-all ${
                  isActive(link.path)
                    ? 'bg-primary/10 text-primary font-bold'
                    : 'text-on-surface-variant hover:bg-surface-container'
                }`}
              >
                <span className="material-symbols-outlined text-lg">{link.icon}</span>
                {link.name}
              </Link>
            ))}
          </div>

          <div className="pt-4 px-4">
            <Link to="/admissions" onClick={() => setMobileMenuOpen(false)} className="block w-full">
              <button className="w-full bg-primary text-on-primary py-3 rounded-full text-base font-semibold shadow-md active:scale-95 transition-all">
                Apply Now
              </button>
            </Link>
          </div>
        </div>
      )}
    </nav>
  );
}
