import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  FaUserCircle,
  FaSignOutAlt,
  FaSignInAlt,
  FaBars,
  FaChevronDown,
  FaGlobe,
  FaWrench,
  FaDownload,
  FaGitAlt,
  FaPlayCircle,
  FaUsers,
  FaHandsHelping,
} from "react-icons/fa";
import {FaClapperboard, FaCubes} from "react-icons/fa6";
import { useAuth } from "@/context/AuthContext";
import styles from "./navbar.module.css";

export default function Navbar() {
  const { user, isAuthenticated, logout } = useAuth();
  const navigate = useNavigate();
  
  const handleLogin = () => navigate("/login");
  const handleLogout = async () => {
    await logout();
    navigate("/");
  };
  const [mobileMenu, setMobileMenu] = useState(false);
  const navRef = useRef<HTMLElement | null>(null);

  // close on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (!navRef.current) return;
      if (!navRef.current.contains(e.target as Node)) {
        // close only mobile menu here; dropdowns are CSS-controlled
      }
    }
    window.addEventListener("click", handleClick);
    return () => window.removeEventListener("click", handleClick);
  }, []);

  // close dropdowns on Escape
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") {
        setMobileMenu(false);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <nav className={`${styles.navbar} ${mobileMenu ? styles.mobileNavOpen : ""}`} ref={navRef} aria-label="Hlavní navigace">
      {/* mobile burger */}
      <button
        className={styles.burger}
        onClick={() => setMobileMenu((p) => !p)}
        aria-expanded={mobileMenu}
        aria-label="Otevřít menu"
      >
        <FaBars />
      </button>
      
      {/* left: brand */}
      <div className={styles.logo}>
        <a href="/" aria-label="vontor.cz home">vontor.cz</a>
      </div>

      

      {/* center links */}
      <div className={`${styles.links} ${mobileMenu ? styles.show : ""}`} role="menubar">
        {/* Services with submenu */}
        <div className={styles.dropdownItem}>
          <button
            className={styles.linkButton}
            aria-haspopup="true"
          >
            <FaHandsHelping className={styles.iconSmall}/> Služby <FaChevronDown className={styles.chev} />
          </button>

          <div className={styles.dropdown} role="menu" aria-label="Služby submenu">
            <a href="/services/web" role="menuitem"><FaGlobe className={styles.iconSmall}/> Weby</a>

            {/* Filmařina as a simple link (no dropdown) */}
            <a href="/services/film" role="menuitem">
              <FaClapperboard className={styles.iconSmall}/> Filmařina
            </a>


            <a href="/services/drone-service" role="menuitem"><FaWrench className={styles.iconSmall}/> Servis dronu</a>
          </div>
        </div>

        {/* Aplikace standalone submenu */}
        <div className={styles.dropdownItem}>
          <button className={styles.linkButton} aria-haspopup="true">
            <FaCubes className={styles.iconSmall}/> Aplikace <FaChevronDown className={styles.chev} />
          </button>
          <div className={styles.dropdown} role="menu" aria-label="Aplikace submenu">
            <a href="/apps/downloader" role="menuitem"><FaDownload className={styles.iconSmall}/> Downloader</a>
            <a href="/apps/git" role="menuitem"><FaGitAlt className={styles.iconSmall}/> Git</a>
            <a href="/apps/dema" role="menuitem"><FaPlayCircle className={styles.iconSmall}/> Dema</a>
            <a href="/apps/social" role="menuitem"><FaUsers className={styles.iconSmall}/> Social</a>
          </div>
        </div>

        <a className={styles.linkSimple} href="#contacts"><FaGlobe className={styles.iconSmall}/> Kontakt</a>
      
        {/* right: user area */}
        {!isAuthenticated ? (
          <a className={styles.linkSimple} onClick={handleLogin} aria-label="Přihlásit">
            <FaSignInAlt className={styles.iconSmall} />
          </a>
        ) : (
          <div className={styles.dropdownItem}>
            <button
              className={styles.linkButton}
              aria-haspopup="true"
            >
              {user.avatarUrl ? (
                <img src={user.avatarUrl} alt={`${user.username} avatar`} className={styles.avatar} />
              ) : (
                <FaUserCircle className={styles.userIcon} />
              )}
              <span className={styles.username}>{user.username}</span>
              <FaChevronDown className={styles.chev}/>
            </button>

            <div className={styles.dropdown} role="menu" aria-label="Uživatelské menu">
              <a href="/me/profile" role="menuitem">Profil</a>
              <a href="/me/settings" role="menuitem">Nastavení</a>
              <a href="/me/billing" role="menuitem">Platby</a>

              <button className={styles.logoutBtn} onClick={handleLogout} role="menuitem">
                <FaSignOutAlt className={styles.iconSmall} /> Odhlásit se
              </button>
            </div>
          </div>
        )}
      </div>


      {/*FIXME: STRČIT USER ČÁST DO LINK SKUPINY ABY TO BYLO KOMPATIBILNI PRO MOBIL*/}
      
    </nav>
  );
}
