import { useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  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 Avatar from "@/components/ui/Avatar";
import styles from "./navbar.module.css";

export default function Navbar() {
  const { user, isAuthenticated, logout } = useAuth();
  const navigate = useNavigate();

  const handleLogin = () => navigate("/social/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}>
        <Link to="/" aria-label="vontor.cz home">vontor.cz</Link>
      </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">
            <Link to="/services/web" role="menuitem">
              <FaGlobe className={styles.iconSmall} /> Weby
            </Link>
            <Link to="/services/film" role="menuitem">
              <FaClapperboard className={styles.iconSmall} /> Filmařina
            </Link>
            <Link to="/services/drone" role="menuitem">
              <FaWrench className={styles.iconSmall} /> Servis dronu
            </Link>
          </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">
            <Link to="/apps/downloader" role="menuitem">
              <FaDownload className={styles.iconSmall} /> Downloader
            </Link>
            <Link to="/apps/git" role="menuitem">
              <FaGitAlt className={styles.iconSmall} /> Git
            </Link>
            <Link to="/apps/dema" role="menuitem">
              <FaPlayCircle className={styles.iconSmall} /> Dema
            </Link>
          </div>
        </div>

        {/* Social entry — top-level link to the social area */}
        <Link className={styles.linkSimple} to="/social/feed">
          <FaUsers className={styles.iconSmall} /> Social
        </Link>

        <Link className={styles.linkSimple} to="/contact">
          <FaGlobe className={styles.iconSmall} /> Kontakt
        </Link>

        {/* right: user area */}
        {!isAuthenticated || !user ? (
          <button
            type="button"
            className={styles.linkSimple}
            onClick={handleLogin}
            aria-label="Přihlásit"
          >
            <FaSignInAlt className={styles.iconSmall} />
          </button>
        ) : (
          <div className={styles.dropdownItem}>
            <button className={styles.linkButton} aria-haspopup="true">
              <Avatar
                name={user.username || user.email}
                size={24}
                className={styles.avatar}
              />
              <span className={styles.username}>{user.username}</span>
              <FaChevronDown className={styles.chev} />
            </button>

            <div className={styles.dropdown} role="menu" aria-label="Uživatelské menu">
              <Link to="/social/profile" role="menuitem">Profil</Link>
              <Link to="/social/feed" role="menuitem">Feed</Link>
              <Link to="/social/chats" role="menuitem">Zprávy</Link>

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