"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";

export default function DisplayNav() {
  const { user, token, logout, loading } = useAuth();
  const { itemCount, selectedStoreId, setStoreId } = useCart();
  const router = useRouter();
  const [stores, setStores] = useState([]);

  useEffect(() => {
    if (!token) return;
    fetch("/api/v1/stores?size=100", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { if (data) setStores(data.content ?? []); })
      .catch(() => {});
  }, [token]);

  function handleLogout() {
    logout();
    router.push("/");
  }

  return (
    <nav className="navbar">
      <Image
        className="mx-3"
        src="/logo_simple.png"
        alt="store_logo"
        width={50}
        height={50}
        id="logo"
      />

      <div className="nav-links">
        <Link href="/" className="nav-link">Home</Link>
        <Link href="/adopt" className="nav-link">Adopt a Pet</Link>
        <Link href="/products" className="nav-link">Online Store</Link>
        <Link href="/appointments" className="nav-link">Schedule an Appointment</Link>
        <Link href="/ai-chat" className="nav-link">AI Assistant</Link>
        <Link href="/contact" className="nav-link">Contact Us</Link>
        <Link href="/about" className="nav-link">About Us</Link>
      </div>

      <div className="nav-auth">
        {stores.length > 0 && (
          <select
            className="nav-store-select"
            value={selectedStoreId ?? ""}
            onChange={(e) => setStoreId(e.target.value || null)}
          >
            <option value="">Select Store</option>
            {stores.map((s) => (
              <option key={s.storeId} value={s.storeId}>
                {s.storeName}
              </option>
            ))}
          </select>
        )}

        {user && (
          <Link href="/cart" className="nav-cart-btn" aria-label="Cart">
            🛒
            {itemCount > 0 && (
              <span className="nav-cart-badge">{itemCount > 99 ? "99+" : itemCount}</span>
            )}
          </Link>
        )}

        {loading ? null : user ? (
          <>
            <Link href="/profile" className="nav-link nav-greeting">
              Hello, {user.fullName || user.username}
            </Link>
            <button type="button" className="nav-logout-btn" onClick={handleLogout}>
              Log Out
            </button>
          </>
        ) : (
          <>
            <Link href="/login" className="nav-link">Log In</Link>
            <Link href="/register" className="nav-link nav-register-btn">Register</Link>
          </>
        )}
      </div>
    </nav>
  );
}
