"use client";

import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";

//Shared CSS class strings for nav links and buttons
const drawerLinkCls = "block text-[#2f2f2f] no-underline text-[1.05rem] font-medium px-2 py-[0.65rem] rounded-md transition-colors hover:bg-[rgba(47,47,47,0.1)]";
const navLinkCls = "text-[#2f2f2f] no-underline text-[1.05rem] font-semibold px-4 py-2 rounded-md transition-all duration-[250ms] hover:bg-white/25";
const cartBtnCls = "relative inline-flex items-center text-[1.4rem] no-underline mr-2 px-[0.4rem] py-[0.2rem] rounded-md transition-colors hover:bg-white/20";
const cartBadgeCls = "absolute -top-1 -right-1.5 bg-[#e53935] text-white rounded-full text-[0.65rem] font-bold min-w-[18px] h-[18px] flex items-center justify-center px-[3px] leading-none";

//Cart icon with a red badge showing the number of items
function CartIcon({ itemCount, onClick }) {
  return (
    <Link href="/cart" className={`${cartBtnCls} group`} aria-label="Cart" onClick={onClick}>
      <span className="relative w-6 h-6 inline-block">
        <img src="/bootstrap/cart.svg" alt="" className="w-6 h-6 absolute inset-0 transition-opacity duration-150 group-hover:opacity-0" />
        <img src="/bootstrap/cart-fill.svg" alt="" className="w-6 h-6 absolute inset-0 transition-opacity duration-150 opacity-0 group-hover:opacity-100" />
      </span>
      {itemCount > 0 && (
        <span className={cartBadgeCls}>{itemCount > 99 ? "99+" : itemCount}</span>
      )}
    </Link>
  );
}

//Top navigation bar - desktop links on the left, store selector and auth on the right, hamburger menu on mobile
export default function DisplayNav() {
  const { user, logout, loading } = useAuth();
  const { itemCount, selectedStoreId, setStoreId } = useCart();
  const router = useRouter();
  const [stores, setStores] = useState([]);
  const [menuOpen, setMenuOpen] = useState(false);

  //Loads the store list for the store selector dropdown
  useEffect(() => {
    fetch("/api/v1/stores?size=100")
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { if (data) setStores(data.content ?? []); })
      .catch(() => {});
  }, []);

  //Logs out and sends the user to the home page
  function handleLogout() {
    logout();
    router.push("/");
    setMenuOpen(false);
  }

  function closeMenu() { setMenuOpen(false); }

  //Store selector dropdown, shared between desktop and mobile layouts
  const storeSelect = (extraCls = "") => stores.length > 0 && (
    <select
      className={`bg-[rgba(47,47,47,0.1)] text-[#2f2f2f] border border-[rgba(47,47,47,0.35)] rounded-md px-[0.6rem] py-[0.3rem] text-[0.9rem] cursor-pointer outline-none transition-colors hover:bg-[rgba(47,47,47,0.2)] ${extraCls}`}
      value={selectedStoreId ?? ""}
      onChange={(e) => { setStoreId(e.target.value || null); if (extraCls) closeMenu(); }}
    >
      <option value="">All Stores</option>
      {stores.map((s) => <option key={s.storeId} value={s.storeId}>{s.storeName}</option>)}
    </select>
  );

  return (
    <nav className="fixed top-0 left-0 w-full bg-[#e68672] shadow-[0_2px_10px_rgba(0,0,0,0.1)] z-[1000] px-8 py-2 grid [grid-template-columns:1fr_auto_1fr] items-center min-h-[70px] max-[1100px]:px-4">
      <Link href="/" onClick={closeMenu}>
        <Image className="mx-3" src="/logo.png" alt="store_logo" width={50} height={50} id="logo" loading="eager" />
      </Link>

      {/* Desktop nav links */}
      <div className="hidden min-[1101px]:flex items-center gap-5 justify-center">
        <Link href="/" className={navLinkCls}>Home</Link>
        <Link href="/adopt" className={navLinkCls}>Adopt</Link>
        <Link href="/products" className={navLinkCls}>Store</Link>
        <Link href="/appointments" className={navLinkCls}>Appointments</Link>
        <Link href="/ai-chat" className={navLinkCls}>Help</Link>
        <Link href="/contact" className={navLinkCls}>Contact</Link>
      </div>

      {/* Desktop auth */}
      <div className="hidden min-[1101px]:flex items-center gap-2 justify-self-end min-w-0 overflow-hidden whitespace-nowrap">
        {storeSelect("mr-2 max-w-[160px]")}
        {user && <CartIcon itemCount={itemCount} />}
        {loading ? null : user ? (
          <>
            <Link href="/profile" className={`${navLinkCls} font-bold`}>
              Hello, {(user.fullName || user.username).split(" ")[0]}
            </Link>
            <button type="button" className="bg-[rgba(47,47,47,0.15)] text-[#2f2f2f] border border-[rgba(47,47,47,0.4)] rounded-full px-4 py-[0.35rem] text-[0.95rem] cursor-pointer transition-colors whitespace-nowrap hover:bg-[rgba(47,47,47,0.25)]" onClick={handleLogout}>
              Log Out
            </button>
          </>
        ) : (
          <>
            <Link href="/login" className={navLinkCls}>Log In</Link>
            <Link href="/register" className="bg-[#2f2f2f] text-[#e68672] font-semibold rounded-full px-4 py-[0.4rem] no-underline transition-colors hover:bg-[#444]">Register</Link>
          </>
        )}
      </div>

      {/* Mobile bar: cart + hamburger */}
      <div className="flex min-[1101px]:hidden items-center gap-2 [grid-column:3] justify-self-end">
        {user && <CartIcon itemCount={itemCount} onClick={closeMenu} />}
        <button
          className={`flex flex-col justify-center gap-[5px] w-9 h-9 bg-transparent border-none cursor-pointer p-1 rounded-md transition-colors hover:bg-[rgba(47,47,47,0.12)]${menuOpen ? " nav-hamburger--open" : ""}`}
          aria-label="Toggle navigation menu"
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen((o) => !o)}
        >
          <span className="block h-[2px] w-full bg-[#2f2f2f] rounded-sm transition-all duration-[250ms] origin-center" />
          <span className="block h-[2px] w-full bg-[#2f2f2f] rounded-sm transition-all duration-[250ms] origin-center" />
          <span className="block h-[2px] w-full bg-[#2f2f2f] rounded-sm transition-all duration-[250ms] origin-center" />
        </button>
      </div>

      {/* Mobile dropdown drawer */}
      {menuOpen && (
        <div className="flex flex-col absolute top-[70px] left-0 w-full bg-[#e68672] px-6 pb-6 pt-4 z-[999] shadow-[0_6px_20px_rgba(0,0,0,0.15)] rounded-b-[10px] gap-1">
          <Link href="/" className={drawerLinkCls} onClick={closeMenu}>Home</Link>
          <Link href="/adopt" className={drawerLinkCls} onClick={closeMenu}>Adopt</Link>
          <Link href="/products" className={drawerLinkCls} onClick={closeMenu}>Store</Link>
          <Link href="/appointments" className={drawerLinkCls} onClick={closeMenu}>Appointments</Link>
          <Link href="/ai-chat" className={drawerLinkCls} onClick={closeMenu}>Help</Link>
          <Link href="/contact" className={drawerLinkCls} onClick={closeMenu}>Contact</Link>

          <div className="h-px bg-[rgba(47,47,47,0.2)] my-2" />

          {storeSelect("w-full mb-1")}

          {loading ? null : user ? (
            <>
              <Link href="/profile" className={drawerLinkCls} onClick={closeMenu}>
                My Profile ({user.fullName || user.username})
              </Link>
              <button type="button" className="w-full bg-[rgba(47,47,47,0.15)] text-[#2f2f2f] border border-[rgba(47,47,47,0.4)] rounded-lg px-4 py-[0.65rem] text-base cursor-pointer transition-colors mt-1 hover:bg-[rgba(47,47,47,0.25)]" onClick={handleLogout}>
                Log Out
              </button>
            </>
          ) : (
            <>
              <Link href="/login" className={drawerLinkCls} onClick={closeMenu}>Log In</Link>
              <Link href="/register" className="block mt-1 bg-[#2f2f2f] text-[#e68672] font-bold rounded-full px-4 py-[0.6rem] text-center no-underline transition-colors hover:bg-[#444]" onClick={closeMenu}>Register</Link>
            </>
          )}
        </div>
      )}
    </nav>
  );
}
