import { useEffect, useState } from "react";
import { Link, useNavigate, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
  FaSignOutAlt, FaSignInAlt, FaBars, FaChevronDown,
  FaCode, FaWrench, FaUsers, FaTimes, FaEnvelope,
} from "react-icons/fa";
import { FaClapperboard } from "react-icons/fa6";
import { useAuth } from "@/hooks/useAuth";
import Avatar from "@/components/ui/Avatar";
import styles from "./navbar.module.css";

export default function Navbar() {
  const { t } = useTranslation("common");
  const { user, isAuthenticated, logout } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const handleLogin  = () => navigate("/social/login");
  const handleLogout = async () => { await logout(); navigate("/"); };

  const [mobileMenu,        setMobileMenu]        = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);
  const [mobileUserOpen,     setMobileUserOpen]     = useState(false);
  const [scrolled,           setScrolled]           = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    setMobileMenu(false);
    setMobileServicesOpen(false);
    setMobileUserOpen(false);
  }, [location.pathname]);

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

  useEffect(() => {
    document.body.style.overflow = mobileMenu ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileMenu]);

  const closeAll = () => setMobileMenu(false);

  return (
    <>
      <nav
        className={`${styles.navbar} ${scrolled ? styles.scrolled : ""}`}
        aria-label={t("nav.mainNav", { defaultValue: "Hlavní navigace" })}
      >
        {/* Brand */}
        <div className={styles.logo}>
          <Link to="/" aria-label="vontor.cz home">vontor.cz</Link>
        </div>

        {/* Desktop links */}
        <div className={styles.links} role="menubar">
          <div className={styles.dropdownItem}>
            <button className={styles.linkButton} aria-haspopup="true" tabIndex={0}>
              {t("nav.services")} <FaChevronDown className={styles.chev} />
            </button>
            <div className={styles.dropdown} role="menu" aria-label={t("nav.services")}>
              <Link to="/services/web"   role="menuitem"><FaCode         className={styles.iconSmall} /> {t("nav.webDev")}</Link>
              <Link to="/services/film"  role="menuitem"><FaClapperboard className={styles.iconSmall} /> {t("nav.filmAerial")}</Link>
              <Link to="/services/drone" role="menuitem"><FaWrench       className={styles.iconSmall} /> {t("nav.droneService")}</Link>
            </div>
          </div>

          <Link className={styles.linkSimple} to="/social/feed">
            <FaUsers className={styles.iconSmall} /> {t("nav.community")}
          </Link>

          <Link className={styles.linkSimple} to="/contact">
            <FaEnvelope className={styles.iconSmall} /> {t("nav.contact")}
          </Link>

          {!isAuthenticated || !user ? (
            <button type="button" className={styles.loginBtn} onClick={handleLogin} aria-label={t("nav.login")}>
              <FaSignInAlt /> {t("nav.login")}
            </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={t("nav.userMenu", { defaultValue: "Uživatelské menu" })}>
                <Link to="/social/profile" role="menuitem">{t("nav.profile")}</Link>
                <Link to="/social/feed"    role="menuitem">{t("nav.feed")}</Link>
                <Link to="/social/chats"   role="menuitem">{t("nav.messages")}</Link>
                <button type="button" className={styles.logoutBtn} onClick={handleLogout} role="menuitem">
                  <FaSignOutAlt className={styles.iconSmall} /> {t("nav.logout")}
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Burger */}
        <button
          className={styles.burger}
          onClick={() => setMobileMenu(p => !p)}
          aria-expanded={mobileMenu}
          aria-label={mobileMenu ? t("nav.closeMenu", { defaultValue: "Zavřít menu" }) : t("nav.openMenu", { defaultValue: "Otevřít menu" })}
        >
          {mobileMenu ? <FaTimes /> : <FaBars />}
        </button>
      </nav>

      {/* Backdrop */}
      <div
        className={`${styles.overlay} ${mobileMenu ? styles.overlayVisible : ""}`}
        onClick={closeAll}
        aria-hidden="true"
      />

      {/* Mobile drawer */}
      <div
        className={`${styles.drawer} ${mobileMenu ? styles.drawerOpen : ""}`}
        aria-hidden={!mobileMenu}
      >
        <div className={styles.drawerHeader}>
          <Link to="/" className={styles.drawerLogo} onClick={closeAll}>vontor.cz</Link>
          <button className={styles.drawerClose} onClick={closeAll} aria-label={t("nav.closeMenu", { defaultValue: "Zavřít menu" })}>
            <FaTimes />
          </button>
        </div>

        <nav className={styles.drawerNav}>
          {/* Služby accordion */}
          <div>
            <button
              className={styles.drawerAccordion}
              onClick={() => setMobileServicesOpen(p => !p)}
              aria-expanded={mobileServicesOpen}
            >
              {t("nav.services")}
              <FaChevronDown className={`${styles.chev} ${mobileServicesOpen ? styles.chevOpen : ""}`} />
            </button>
            <div className={`${styles.drawerSub} ${mobileServicesOpen ? styles.drawerSubOpen : ""}`}>
              <Link to="/services/web"   className={styles.drawerSubItem} onClick={closeAll}><FaCode         className={styles.iconSmall} /> {t("nav.webDev")}</Link>
              <Link to="/services/film"  className={styles.drawerSubItem} onClick={closeAll}><FaClapperboard className={styles.iconSmall} /> {t("nav.filmAerial")}</Link>
              <Link to="/services/drone" className={styles.drawerSubItem} onClick={closeAll}><FaWrench       className={styles.iconSmall} /> {t("nav.droneService")}</Link>
            </div>
          </div>

          <Link to="/social/feed" className={styles.drawerItem} onClick={closeAll}>
            <FaUsers className={styles.iconSmall} /> {t("nav.community")}
          </Link>

          <Link to="/contact" className={styles.drawerItem} onClick={closeAll}>
            <FaEnvelope className={styles.iconSmall} /> {t("nav.contact")}
          </Link>

          <div className={styles.drawerDivider} />

          {!isAuthenticated || !user ? (
            <button
              type="button"
              className={styles.drawerLoginBtn}
              onClick={() => { handleLogin(); closeAll(); }}
            >
              <FaSignInAlt /> {t("nav.login")}
            </button>
          ) : (
            <div>
              <button
                className={styles.drawerAccordion}
                onClick={() => setMobileUserOpen(p => !p)}
                aria-expanded={mobileUserOpen}
              >
                <Avatar name={user.username || user.email} size={28} className={styles.avatar} />
                <span className={styles.username}>{user.username}</span>
                <FaChevronDown className={`${styles.chev} ${mobileUserOpen ? styles.chevOpen : ""}`} />
              </button>
              <div className={`${styles.drawerSub} ${mobileUserOpen ? styles.drawerSubOpen : ""}`}>
                <Link to="/social/profile" className={styles.drawerSubItem} onClick={closeAll}>{t("nav.profile")}</Link>
                <Link to="/social/feed"    className={styles.drawerSubItem} onClick={closeAll}>{t("nav.feed")}</Link>
                <Link to="/social/chats"   className={styles.drawerSubItem} onClick={closeAll}>{t("nav.messages")}</Link>
                <button
                  type="button"
                  className={`${styles.drawerSubItem} ${styles.drawerLogout}`}
                  onClick={() => { handleLogout(); closeAll(); }}
                >
                  <FaSignOutAlt className={styles.iconSmall} /> {t("nav.logout")}
                </button>
              </div>
            </div>
          )}
        </nav>
      </div>
    </>
  );
}
