import React, { useState, useEffect, useRef } from "react";
import { FaUserCircle, FaBars, FaTimes, FaSun, FaMoon, FaChevronDown } from "react-icons/fa";
import { useTheme } from "../contexts/ThemeContext";
import { useNavigate } from "react-router-dom";
import eflLogo from "../assets/EFL.png";
import efdLogo from "../assets/EFD.png";
import ChangePasswordModal from "./ChangePasswordModal";

const Navbar = ({ onMobileMenuToggle, isMobileMenuOpen }) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [userName, setUserName] = useState("User");
  const [isChangePasswordModalOpen, setIsChangePasswordModalOpen] = useState(false);
  const mobileDropdownRef = useRef(null);
  const desktopDropdownRef = useRef(null);
  const { toggleTheme, isLight } = useTheme();
  const navigate = useNavigate();

  const toggleDropdown = () => setIsDropdownOpen(!isDropdownOpen);

  const toggleMobileMenu = () => {
    if (onMobileMenuToggle) {
      onMobileMenuToggle();
    }
  };

  // Get user data from localStorage on component mount
  useEffect(() => {
    const userData = localStorage.getItem("user");
    if (userData) {
      try {
        const user = JSON.parse(userData);
        // Display username, email, or name based on what's available
        const displayName = user.username || user.email || user.name || "User";
        setUserName(displayName);
      } catch (error) {
        console.error("Error parsing user data:", error);
        setUserName("User");
      }
    }
  }, []);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      const clickedInsideMobile =
        mobileDropdownRef.current &&
        mobileDropdownRef.current.contains(event.target);
      const clickedInsideDesktop =
        desktopDropdownRef.current &&
        desktopDropdownRef.current.contains(event.target);

      if (!clickedInsideMobile && !clickedInsideDesktop) {
        setIsDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleLogout = () => {
    // Clear user data and any stored route information
    localStorage.removeItem("user");

    // Clear any form persistence data to ensure clean state
    const keysToRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (
        key &&
        (key.startsWith("formData_") || key.startsWith("activeSection"))
      ) {
        keysToRemove.push(key);
      }
    }
    keysToRemove.forEach((key) => localStorage.removeItem(key));

    // Clear any session storage as well
    sessionStorage.clear();

    // Use React Router navigation with replace to prevent back navigation
    // This ensures proper routing and prevents history preservation issues
    navigate("/", { replace: true });
  };

  // Theme-based styling
  const navbarBg = isLight
    ? "bg-yellow-400"
    : "bg-slate-800 border-b border-slate-700";

  const textColor = isLight ? "text-gray-800" : "text-slate-100";
  const hoverBg = isLight ? "hover:bg-yellow-300/20" : "hover:bg-slate-700";

  return (
    <nav
      className={`${navbarBg} h-16 flex items-center justify-between px-4 sm:px-6 shadow-lg fixed w-full top-0 z-50 transition-all duration-300`}
    >
      {/* Left side - Profile (mobile only) and Logo */}
      <div className="flex items-center space-x-2">
        {/* Profile Section - Mobile only */}
        <div className="relative sm:hidden" ref={mobileDropdownRef}>
          <button
            onClick={toggleDropdown}
            className={`flex items-center gap-2 focus:outline-none ${hoverBg} rounded-lg px-2 py-1 transition-colors`}
          >
            <FaUserCircle className={`text-2xl ${textColor}`} />
            <FaChevronDown className={`text-lg ${textColor}`} />
          </button>

          {isDropdownOpen && (
            <div className="absolute left-0 mt-2 w-40 bg-white dark:bg-slate-800 rounded-md shadow-lg dark:shadow-2xl z-50 border dark:border-slate-700">
              <div className="px-4 py-2 text-sm text-gray-600 dark:text-slate-300 border-b dark:border-slate-700">
                <div className="font-medium text-gray-800 dark:text-slate-100 truncate">
                  {userName}
                </div>
              </div>
              <button
                onClick={() => {
                  setIsChangePasswordModalOpen(true);
                  setIsDropdownOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-50 transition-colors"
                style={{ backgroundColor: isLight ? 'transparent' : '#1e293b' }}
                onMouseEnter={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#334155';
                }}
                onMouseLeave={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#1e293b';
                }}
              >
                Change Password
              </button>
              <button
                onClick={handleLogout}
                className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 transition-colors"
                style={{ backgroundColor: isLight ? 'transparent' : '#1e293b' }}
                onMouseEnter={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#334155';
                }}
                onMouseLeave={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#1e293b';
                }}
              >
                Logout
              </button>
            </div>
          )}
        </div>

        {/* Logo & Title */}
        <div className="flex items-center">
          <img
            src={isLight ? eflLogo : efdLogo}
            alt="Kartavya Logo"
            className="h-12 w-12 sm:h-16 sm:w-16 lg:h-20 lg:w-20 object-contain"
          />
        </div>
      </div>

      {/* Right side - Theme toggle, Profile Section, and Mobile menu button */}
      <div className="flex items-center space-x-2">
        {/* Theme Toggle Button */}
        <button
          onClick={toggleTheme}
          className={`p-2 ${hoverBg} rounded-lg transition-all duration-300 ${textColor} hover:scale-105 active:scale-95 flex items-center justify-center w-10 h-10`}
          aria-label={`Switch to ${isLight ? "dark" : "light"} mode`}
          title={`Switch to ${isLight ? "dark" : "light"} mode`}
        >
          {isLight ? (
            <FaMoon className="text-xl flex-shrink-0" />
          ) : (
            <FaSun className="text-xl text-cyan-400 flex-shrink-0" />
          )}
        </button>

        {/* Profile Section - Desktop only */}
        <div className="relative hidden sm:block" ref={desktopDropdownRef}>
          <button
            onClick={toggleDropdown}
            className={`flex items-center gap-2 focus:outline-none ${hoverBg} rounded-lg px-2 py-1 transition-colors`}
          >
            <FaUserCircle className={`text-2xl sm:text-3xl ${textColor}`} />
            <span
              className={`hidden sm:block ${textColor} font-medium text-sm lg:text-base truncate max-w-24 lg:max-w-none`}
            >
              {userName}
            </span>
            <FaChevronDown className={`text-lg ${textColor}`} />
          </button>

          {isDropdownOpen && (
            <div className="absolute right-0 mt-2 w-40 bg-white dark:bg-slate-800 rounded-md shadow-lg dark:shadow-2xl z-50 border dark:border-slate-700">
              <button
                onClick={() => {
                  setIsChangePasswordModalOpen(true);
                  setIsDropdownOpen(false);
                }}
                className="block w-full text-left px-4 py-2 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-50 transition-colors"
                style={{ backgroundColor: isLight ? 'transparent' : '#1e293b' }}
                onMouseEnter={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#334155';
                }}
                onMouseLeave={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#1e293b';
                }}
              >
                Change Password
              </button>
              <button
                onClick={handleLogout}
                className="block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 transition-colors"
                style={{ backgroundColor: isLight ? 'transparent' : '#1e293b' }}
                onMouseEnter={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#334155';
                }}
                onMouseLeave={(e) => {
                  if (!isLight) e.target.style.backgroundColor = '#1e293b';
                }}
              >
                Logout
              </button>
            </div>
          )}
        </div>

        {/* Mobile Menu Button - Only visible on mobile */}
        <button
          onClick={toggleMobileMenu}
          className={`lg:hidden ${textColor} text-xl p-2 ${hoverBg} rounded transition-colors flex items-center justify-center w-10 h-10`}
          aria-label="Toggle mobile menu"
        >
          {isMobileMenuOpen ? <FaTimes className="flex-shrink-0" /> : <FaBars className="flex-shrink-0" />}
        </button>
      </div>

      {/* Change Password Modal */}
      <ChangePasswordModal
        isOpen={isChangePasswordModalOpen}
        onClose={() => setIsChangePasswordModalOpen(false)}
      />
    </nav>
  );
};

export default Navbar;
