import React, { useState, useEffect, useContext, useCallback } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { User, ChevronDown, LogOut, Landmark, Building2, Users } from 'lucide-react';
import { AuthContext } from '../auth/AuthContext.jsx'; // Adjust the import path to match your file structure (e.g., '../contexts/AuthContext' or wherever authcontext.js is)
import CourtOfArms from '../assets/Court of Arms.png';
import Footer from "../components/Footer";

// Ministries, Organizations, Agencies (imported from CitizenHomePage for DRY, but here hardcoded for now)
const ministries = [
  "Ministry of Agriculture, Animal Industry and Fisheries",
  "Ministry of Defence and Veteran Affairs",
  "Ministry of Education and Sports",
  "Ministry of Energy and Mineral Development",
  "Ministry of Finance, Planning and Economic Development",
  "Ministry of Foreign Affairs",
  "Ministry of Gender, Labour and Social Development",
  "Ministry of Health",
  "Ministry of Information and Communications Technology",
  "Ministry of Internal Affairs",
  "Ministry of Justice and Constitutional Affairs",
  "Ministry of Lands, Housing and Urban Development",
  "Ministry of Local Government",
  "Ministry of Public Service",
  "Ministry of Tourism, Wildlife and Antiquities",
  "Ministry of Trade, Industry and Cooperatives",
  "Ministry of Transport and Works",
  "Ministry of Water and Environment",
];
const organizations = [
  "National Social Security Fund (NSSF)",
  "Uganda Electricity Distribution Company Limited (UEDCL)",
  "Uganda National Roads Authority (UNRA)",
  "Uganda Revenue Authority (URA)",
  "National Identification and Registration Authority (NIRA)",
  "Uganda Communications Commission (UCC)",
  "National Water and Sewerage Corporation (NWSC)",
  "Uganda Development Bank Limited (UDBL)",
];
const agencies = [
  "Electoral Commission",
  "Inspectorate of Government",
  "National Environment Management Authority (NEMA)",
  "Uganda Human Rights Commission",
  "Equal Opportunities Commission",
  "Public Procurement and Disposal of Public Assets Authority",
];

const Navbar = () => {
  const { auth, logout } = useContext(AuthContext); // Use AuthContext to get auth state and logout function
  const user = auth; // auth holds the user object (or null)
  const isAuthenticated = !!auth; // Simple check: if auth exists, user is logged in

  const location = useLocation();
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [mobileExpandedCategory, setMobileExpandedCategory] = useState(null);
  const [showUserDropdown, setShowUserDropdown] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState(null);
  const [dropdownTimeout, setDropdownTimeout] = useState(null);
  const navigate = useNavigate();

  // Insert these new functions:
const scrollToServices = useCallback(() => {
  // Small delay to ensure DOM is updated after navigation
  setTimeout(() => {
    const element = document.getElementById('services');
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }, 100);
}, []);

// Listen for route changes and scroll if hash is #services
useEffect(() => {
  if (location.hash === '#services') {
    scrollToServices();
  }
}, [location.hash, scrollToServices]);

// Handle "Get Started" click for authenticated users
const handleGetStartedClick = useCallback(() => {
  navigate('/', { replace: true }); // Navigate to home (forces route event even if already there)
  scrollToServices(); // Then scroll
}, [navigate, scrollToServices]);

  // Hide dropdown on scroll
  useEffect(() => {
    const handleScroll = () => {
      setActiveDropdown(null);
    };
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
      if (dropdownTimeout) {
        clearTimeout(dropdownTimeout);
      }
    };
  }, [dropdownTimeout]);


  const dropdownSections = [
    {
      title: 'Services',
      links: [
        { label: 'File Complaint', to: '/complaints' },
        { label: 'Polls & Surveys', to: '/polls-surveys' },
        //{ label: 'Feedback', to: '/feedback' },
        { label: 'Chatbot', to: '/chatbot' },
      ],
    },
    {
      title: 'Ministries',
      links: ministries.map(m => ({ label: m, to: '#' })),
    },
    {
      title: 'Organizations',
      links: organizations.map(o => ({ label: o, to: '#' })),
    },
    {
      title: 'Agencies',
      links: agencies.map(a => ({ label: a, to: '#' })),
    },
    {
      title: 'More',
      links: [
        { label: 'About', to: '/Footer' },
        { label: 'Contact', to: '/Footer' },
        { label: 'Help & Support', to: '/Footer' },
      ],
    },
  ];



  const handleCategoryHover = (category) => {
    if (dropdownTimeout) {
      clearTimeout(dropdownTimeout);
      setDropdownTimeout(null);
    }
    setActiveDropdown(category);
  };

  const handleCategoryLeave = () => {
    const timeout = setTimeout(() => {
      setActiveDropdown(null);
    }, 300);
    setDropdownTimeout(timeout);
  };

  const handleDropdownEnter = () => {
    if (dropdownTimeout) {
      clearTimeout(dropdownTimeout);
      setDropdownTimeout(null);
    }
  };

  const handleDropdownLeave = () => {
    const timeout = setTimeout(() => {
      setActiveDropdown(null);
    }, 300);
    setDropdownTimeout(timeout);
  };

  const handleCategoryClick = (category) => {
    if (window.innerWidth < 1024) {
      setActiveDropdown(activeDropdown === category ? null : category);
    } else {
      setActiveDropdown(activeDropdown === category ? null : category);
    }
  };

  return (
  <nav className="bg-white font-sans border-b border-gray-200 w-full">
      {/* Top Row */}
  <div className="w-full flex items-center justify-between py-3 px-4 md:px-8">
        {/* Logo and GCIC */}
        <div className="flex items-center space-x-3">
          <img src={CourtOfArms} alt="Court of Arms" className="h-10 w-auto" />
          <Link to="/" className="text-2xl font-extrabold text-green-700">GCIC</Link>
        </div>
        {/* Desktop Auth */}
        <div className="hidden md:flex items-center space-x-4">
          {isAuthenticated && (
            <div className="relative">
              <button
                onClick={() => setShowUserDropdown(!showUserDropdown)}
                className="flex items-center space-x-2 text-gray-700 hover:text-blue-600 p-2 rounded-full hover:bg-gray-50"
              >
                <User size={20} />
                <span className="text-sm font-medium">{user?.firstName || 'Account'}</span>
                <ChevronDown size={16} />
              </button>
              {showUserDropdown && (
                <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 z-50">
                  {/* Role-based links here */}
                  <Link to="/profile" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-50">Profile</Link>
                  <Link to="/settings" className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-50">Settings</Link>
                  <button onClick={logout} className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center"><LogOut size={16} className="mr-2" />Sign Out</button>
                </div>
              )}
            </div>
          )}
          {isAuthenticated ? (
  <button
    onClick={handleGetStartedClick}  // <-- New: Uses custom handler
    className="bg-blue-800 text-white px-8 py-2 rounded-lg font-semibold hover:bg-blue-900 transition-colors duration-300 shadow-sm"
  >
    Get Started
  </button>
) : (
  <Link
    to="/register"
    className="bg-blue-800 text-white px-8 py-2 rounded-lg font-semibold hover:bg-blue-900 transition-colors duration-300 shadow-sm"
  >
    Get Started
  </Link>
)}
        </div>
        {/* Hamburger for mobile */}
        <button
          className="md:hidden flex items-center px-3 py-2 border rounded text-blue-800 border-blue-800"
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          aria-label="Toggle navigation menu"
        >
          <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={isMobileMenuOpen ? 'M6 18L18 6M6 6l12 12' : 'M4 6h16M4 12h16M4 18h16'} />
          </svg>
        </button>
      </div>
      {/* Second Row: Direct Dropdowns */}
      {/* Desktop Second Row: Direct Dropdowns */}
      <div className="bg-blue-600 text-white border-t border-gray-200 relative w-full hidden md:block">
        <div className="w-full flex items-center py-2 px-0 md:px-0 space-x-6 overflow-x-auto">
          {dropdownSections.map(section => (
            <div
              key={section.title}
              className="relative group"
              onMouseEnter={() => handleCategoryHover(section.title)}
              onMouseLeave={handleCategoryLeave}
            >
              <button
                className={`whitespace-nowrap text-white font-medium transition-colors duration-300 text-sm py-2 px-2 rounded-md focus:outline-none hover:bg-gray-50 hover:text-blue-600 ${
                  activeDropdown === section.title ? 'text-blue-600 bg-blue-50' : 'text-gray-700'
                }`}
                aria-haspopup="true"
                aria-expanded={activeDropdown === section.title}
              >
                {section.title}
                <ChevronDown 
                  size={14} 
                  className={`inline ml-1 transition-transform duration-200 ${activeDropdown === section.title ? 'rotate-180' : ''}`} 
                />
              </button>
            </div>
          ))}
        </div>
        {/* Full-width dropdown below navbar, left-aligned, 3 rows per column */}
        {activeDropdown && (
          <div
            className="absolute left-0 w-full bg-white shadow-lg border-t border-gray-200 z-[100] animate-fade-in"
            style={{ top: '100%' }}
            onMouseEnter={handleDropdownEnter}
            onMouseLeave={handleDropdownLeave}
          >
            <div className="w-full px-0 py-6 flex justify-start">
              {activeDropdown === 'Ministries' ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-x-8 gap-y-1 w-full px-4 max-h-96 overflow-y-auto">
                  {dropdownSections.find(s => s.title === 'Ministries').links.map((link, idx) => (
                    <div key={link.label} className="text-left min-w-0 max-w-xs">
                      <Link to={link.to} className="block text-sm text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded px-2 py-1.5 transition-colors duration-150 whitespace-normal break-words border-b border-gray-100 last:border-b-0">
                        {link.label}
                      </Link>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="flex flex-wrap gap-8 items-start w-full px-4 max-h-96 overflow-y-auto">
                  {(() => {
                    const links = dropdownSections.find(s => s.title === activeDropdown)?.links || [];
                    // Split links into columns of 3
                    const columns = [];
                    for (let i = 0; i < links.length; i += 3) {
                      columns.push(links.slice(i, i + 3));
                    }
                    return columns.map((col, idx) => (
                      <div key={idx} className="min-w-[180px] flex flex-col space-y-1 text-left">
                        {col.map(link => (
                          <Link key={link.label} to={link.to} className="block text-sm text-left text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded px-2 py-1.5 transition-colors duration-150 whitespace-nowrap border-b border-gray-100 last:border-b-0">
                            {link.label}
                          </Link>
                        ))}
                      </div>
                    ));
                  })()}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
      {/* Mobile Menu */}
      {isMobileMenuOpen && (
        <div className="md:hidden fixed inset-0 z-[200] bg-black bg-opacity-40 w-full">
          <div className="absolute top-0 left-0 w-full max-w-full h-full bg-white shadow-lg flex flex-col">
            <div className="flex items-center justify-between px-4 py-4 border-b w-full">
              <div className="flex items-center space-x-2">
                <img src={CourtOfArms} alt="Court of Arms" className="h-8 w-auto" />
                <Link to="/" className="text-xl font-extrabold text-green-700" onClick={() => setIsMobileMenuOpen(false)}>GCIC</Link>
              </div>
              <button onClick={() => setIsMobileMenuOpen(false)} className="text-gray-700 p-2 rounded hover:bg-gray-100">
                <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="flex flex-col px-4 py-6 space-y-2 w-full">
              {dropdownSections.map(section => (
                <div key={section.title} className="w-full">
                  <button
                    className="w-full flex items-center justify-between py-3 px-2 text-gray-700 hover:text-blue-600 text-base font-medium bg-gray-50 hover:bg-blue-50 rounded-lg transition-colors duration-200"
                    onClick={() => setMobileExpandedCategory(mobileExpandedCategory === section.title ? null : section.title)}
                  >
                    {section.title}
                    <ChevronDown
                      size={16}
                      className={`transition-transform duration-200 ${mobileExpandedCategory === section.title ? 'rotate-180' : ''}`}
                    />
                  </button>
                  {/* Mobile Dropdown */}
                  {mobileExpandedCategory === section.title && (
                    <div className="ml-2 mt-2 space-y-1 w-full max-h-80 overflow-y-auto">
                      {section.links.map(link => (
                        <Link
                          key={link.label}
                          to={link.to}
                          className="block py-2 px-3 text-sm text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors duration-200 w-full text-left border-b border-gray-100 last:border-b-0"
                          onClick={() => setIsMobileMenuOpen(false)}
                        >
                          {link.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ))}
              <div className="pt-4 w-full flex flex-col space-y-2">
                {isAuthenticated ? (
  <button
    onClick={() => {
      handleGetStartedClick();  // <-- New: Uses custom handler
      setIsMobileMenuOpen(false);
    }}
    className="block w-full bg-blue-800 text-white py-3 rounded-full font-medium hover:bg-blue-900 transition-colors text-center"
  >
    Get Started
  </button>
) : (
  <Link
    to="/register"
    onClick={() => setIsMobileMenuOpen(false)}
    className="block w-full bg-blue-800 text-white py-3 rounded-full font-medium hover:bg-blue-900 transition-colors text-center"
  >
    Get Started
  </Link>
)}
                {isAuthenticated && (
                  <button
                    onClick={() => {
                      logout();
                      setIsMobileMenuOpen(false);
                    }}
                    className="w-full py-3 text-red-600 hover:text-red-800 font-medium transition-colors"
                  >
                    Sign Out
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};

export default Navbar;