"use client";

import React, { useEffect, useState } from "react";
import NavHead from "./NavHead";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@radix-ui/react-dropdown-menu";
import { useTranslation } from "@/lib/i18n";

const Navbar = () => {
  const [token, setToken] = useState(null);
  const [name, setName] = useState("");
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const router = useRouter();
  const pathname = usePathname();
  const { t } = useTranslation("navbar");

  // ✅ Fetch token & name safely on client-side
  useEffect(() => {
    const storedToken = localStorage.getItem("sadu_auth_token");
    const storedName = localStorage.getItem("name");
    setToken(storedToken);
    setName(storedName);

    const routes = [
      "/",
      "/about",
      "/services",
      "/service/buying-and-selling",
      "/service/rentals-and-management",
      "/service/valuation-and-Advisory",
      "/service/luxury-properties",
      "/service/new-developments",
      "/service/hoa-and-facility-management",
      "/properties",
      "/blogs",
      "/contact",
      "/login",
      "/signup",
    ];

    routes.forEach((route) => router.prefetch(route));
  }, [router]);

  // ✅ Handle Logout
  const handleLogout = () => {
    localStorage.removeItem("sadu_auth_token");
    localStorage.removeItem("name");
    setToken(null);
    setName("");
    router.push("/home");
  };

  const isActive = (path) => pathname === path;

  const navLinks = (
    <>
      <Link
        href="/home"
        className={`${isActive("/home") ? "bg-[#EB5A3C4D]" : ""} px-3 py-1 rounded-full me-0`}
      >
        {t("Home")}
      </Link>

      <Link
        href="/about"
        className={`${isActive("/about") ? "bg-[#EB5A3C4D]" : ""} px-3 py-1 rounded-full me-0`}
      >
        {t("About")}
      </Link>

      <DropdownMenu>
        <DropdownMenuTrigger className="active:outline-0" asChild>
          <Button
            variant="ghost"
            className={`px-0 font-normal me-0 cursor-pointer h-[32px] md:h-[32px] text-[16px] ${
              pathname.startsWith("/service")
                ? "bg-[#EB5A3C4D] hover:bg-[#EB5A3C4D] px-3 py-1 me-0 rounded-full"
                : "hover:bg-transparent"
            }`}
          >
            {t("Services")}
            <svg
              className="w-4 h-4 mt-[2px]"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
            </svg>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent className="w-56 px-5 py-3 shadow rounded-xl z-50 bg-white min-w-[300px]">
          {[
            { href: "/services", label: t("Services") },
            { href: "/service/buying-and-selling", label: t("Buying & Selling") },
            { href: "/service/rentals-and-management", label: t("Rentals & Management") },
            { href: "/service/valuation-and-Advisory", label: t("Valuation & Advisory") },
            { href: "/service/luxury-properties", label: t("Luxury Properties") },
            { href: "/service/new-developments", label: t("New Developments") },
            { href: "/service/hoa-and-facility-management", label: t("HOA & Facility Management") },
          ].map(({ href, label }) => (
            <Link
              key={href}
              href={href}
              className={`block w-full focus:outline-0 hover:bg-primary hover:text-white rounded px-2 py-1 mb-1 ${
                isActive(href) ? "bg-primary text-white" : ""
              }`}
            >
              {label}
            </Link>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>

      <Link
        href="/properties"
        className={`${isActive("/properties") ? "bg-[#EB5A3C4D]" : ""} px-3 py-1 rounded-full me-0`}
      >
        {t("Properties")}
      </Link>

      <Link
        href="/blogs"
        className={`${isActive("/blogs") ? "bg-[#EB5A3C4D]" : ""} px-3 py-1 rounded-full me-0`}
      >
        {t("Blog")}
      </Link>

      <Link
        href="/contact"
        className={`${isActive("/contact") ? "bg-[#EB5A3C4D]" : ""} px-3 py-1 rounded-full me-0`}
      >
        {t("Contact")}
      </Link>

      <div className="flex items-center gap-1 me-0">
        {token ? (
          <DropdownMenu>
            <DropdownMenuTrigger className="active:outline-0" asChild>
              <Button
                variant="ghost"
                className={`px-0 font-normal me-0 cursor-pointer h-[32px] md:h-[32px] text-[16px] ${
                  pathname.startsWith("/profile")
                    ? "bg-[#EB5A3C4D] hover:bg-[#EB5A3C4D] px-3 py-1 me-0 rounded-full"
                    : "hover:bg-transparent"
                }`}
              >
                <div className="relative h-[18px] w-[18px]">
                  <Image src="/icons/person.png" fill alt="sadu-logo" />
                </div>
                {name}
                <svg
                  className="w-4 h-4 mt-[2px]"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                </svg>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent className="w-56 px-5 py-3 shadow rounded-xl z-50 bg-white">
              <button
                onClick={handleLogout}
                className="block w-full text-left hover:bg-primary hover:text-white rounded px-2 py-1 mb-1"
              >
                Logout
              </button>
              <Link
                href="/profile"
                className={`block w-full focus:outline-0 hover:bg-primary hover:text-white rounded px-2 py-1 mb-1 ${
                  isActive("/profile") ? "bg-primary text-white" : ""
                }`}
              >
                View Profile
              </Link>
            </DropdownMenuContent>
          </DropdownMenu>
        ) : (
          <div className="flex items-center justify-center text-[16px]">
            <div className="relative w-[18px] h-[18px]">
              <Image src="/icons/person.png" fill alt="sadu-logo" />
            </div>
            <div className="flex items-center justify-center ps-1 text-[14px] md:text-[16px]">
              <Link href="/login">{t("Login")}</Link>/
              <Link href="/signup">{t("Register")}</Link>
            </div>
          </div>
        )}
      </div>

      <Link href="/contact">
        <Button className="bg-primary ms-2 md:h-[44px]">{t("Click Me")}</Button>
      </Link>
    </>
  );

  return (
    <div>
      <NavHead />
      <div className="flex items-center justify-between px-5 md:px-[50px] lg:px-[96px] py-[10px]">
        <Link
          href="/home"
          className="relative w-[40px] h-[40px] md:w-[60px] md:h-[60px] block"
        >
          <Image
            src="/images/sadu-logo.png"
            fill
            alt="sadu-logo"
            className="cursor-pointer object-contain"
          />
        </Link>

        <div className="hidden lg:flex items-center space-x-4 ms-1">
          {navLinks}
        </div>

        <div className="lg:hidden">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          >
            {isMobileMenuOpen ? (
              <Image src="/icons/close.png" width={18} height={18} alt="close" />
            ) : (
              <Image src="/icons/menu.png" width={25} height={25} alt="menu" />
            )}
          </Button>
        </div>
      </div>

      {isMobileMenuOpen && (
        <div className="absolute top-[120px] right-0 w-[250px] z-20 rounded-l-2xl">
          <div className="lg:hidden rounded-tl-2xl rounded-bl-2xl flex flex-col items-start px-6 py-4 gap-3 bg-white shadow">
            {navLinks}
          </div>
        </div>
      )}
    </div>
  );
};

export default Navbar;
