import "../../styles/components/Navbar.css";

import { useContext, useState } from "react";
import { Link } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import HouseholdSwitcher from "../household/HouseholdSwitcher";

export default function Navbar() {
  const { role, logout, username } = useContext(AuthContext);
  const [showNavMenu, setShowNavMenu] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);

  const closeMenus = () => {
    setShowNavMenu(false);
    setShowUserMenu(false);
  };

  return (
    <nav className="navbar">
      {/* Left: Navigation Menu */}
      <div className="navbar-section navbar-left">
        <button
          className="navbar-menu-btn"
          onClick={() => {
            setShowNavMenu(!showNavMenu);
            setShowUserMenu(false);
          }}
          aria-label="Navigation menu"
        >
          <span className="hamburger-icon">
            <span></span>
            <span></span>
            <span></span>
          </span>
        </button>

        {showNavMenu && (
          <>
            <div className="menu-overlay" onClick={closeMenus}></div>
            <div className="navbar-dropdown nav-dropdown">
              <Link to="/" onClick={closeMenus}>Home</Link>
              <Link to="/manage" onClick={closeMenus}>Manage</Link>
              <Link to="/settings" onClick={closeMenus}>Settings</Link>
              {role === "system_admin" && <Link to="/admin" onClick={closeMenus}>Admin</Link>}
            </div>
          </>
        )}
      </div>

      {/* Center: Household Switcher */}
      <div className="navbar-section navbar-center">
        <HouseholdSwitcher />
      </div>

      {/* Right: User Menu */}
      <div className="navbar-section navbar-right">
        <button
          className="navbar-user-btn"
          onClick={() => {
            setShowUserMenu(!showUserMenu);
            setShowNavMenu(false);
          }}
        >
          {username}
        </button>

        {showUserMenu && (
          <>
            <div className="menu-overlay" onClick={closeMenus}></div>
            <div className="navbar-dropdown user-dropdown">
              <div className="user-dropdown-info">
                <span className="user-dropdown-username">{username}</span>
                <span className="user-dropdown-role">{role}</span>
              </div>
              <button className="user-dropdown-logout" onClick={() => { logout(); closeMenus(); }}>
                Logout
              </button>
            </div>
          </>
        )}
      </div>
    </nav>
  );
}