"use client";

import { useState, useEffect, useRef } from "react";
import { useSession, signOut } from "next-auth/react";
import { Menu, X, Crown, ChevronDown } from "lucide-react";
import { Link, usePathname } from "@/routing";
import NextLink from "next/link";
import Image from "next/image";
import LanguageSwitcher from "./LanguageSwitcher";
import { useTranslations } from "next-intl";

export default function Navbar() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isServicesOpen, setIsServicesOpen] = useState(false);
  const [isMobileServicesOpen, setIsMobileServicesOpen] = useState(false);
  const servicesRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const { data: session } = useSession();
  const t = useTranslations("Navigation");

  // Determine if the current page has a hero section at the top
  const hasHeroPages = ["/", "/tour", "/flight", "/car-rental", "/event", "/about-us", "/gallery", "/contact"];
  const isExactMatch = hasHeroPages.includes(pathname);
  const transparentOnTop = isExactMatch;

  useEffect(() => {
    if (!transparentOnTop) {
      return;
    }

    const handleScroll = () => {
      setIsScrolled(window.scrollY > 10);
    };

    handleScroll();

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, [transparentOnTop]);

  const showSolid = !transparentOnTop || isScrolled;

  useEffect(() => {
    if (isMobileMenuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }
  }, [isMobileMenuOpen]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (servicesRef.current && !servicesRef.current.contains(event.target as Node)) {
        setIsServicesOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const serviceLinks = [
    { name: t("tour"), href: "/tour" },
    { name: t("flight"), href: "/flight" },
    { name: t("carRental"), href: "/car-rental" },
    { name: t("event"), href: "/event" },
  ];

  const navLinks = [
    { name: t("home"), href: "/" },
    { name: t("about"), href: "/about-us" },
    { name: t("gallery"), href: "/gallery" },
    { name: t("contact"), href: "/contact" },
  ];

  const membershipPortalUrl = "https://ranata-membership.vercel.app/#beranda";

  const isActive = (href: string) => {
    if (href === "/") {
      return pathname === "/";
    }
    return pathname.startsWith(href);
  };

  const isServicesActive = serviceLinks.some((link) => isActive(link.href));

  const linkClassName = (active: boolean) =>
    `text-sm transition relative py-2 ${active ? "font-semibold" : "hover:opacity-80"} ${
      active && showSolid
        ? "after:absolute after:bottom-0 after:left-0 after:w-full after:h-[2px] after:bg-merah-ranata"
        : ""
    } ${
      active && !showSolid
        ? "after:absolute after:bottom-0 after:left-0 after:w-full after:h-[2px] after:bg-white"
        : ""
    }`;

  return (
    <>
      <nav
        className={`fixed top-0 left-0 right-0 z-50 transition duration-300 ${
          showSolid
            ? "bg-white shadow-md text-heading"
            : "bg-transparent text-white"
        }`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-20">
            <div className="flex-shrink-0 flex items-center">
              <Link href="/" className="flex items-center gap-3">
                <Image
                  src="/images/logo.svg"
                  alt="Ranata Tour Logo"
                  width={42}
                  height={42}
                  className="rounded flex-shrink-0"
                />
                {/* Logo Text */}
                <span className="font-bold text-2xl tracking-tight font-sans">
                  <span className={showSolid ? "text-gray-800" : "text-white"}>Ranata</span>
                  <span className={showSolid ? "text-[#9e1c1c]" : "text-[#ff8080]"}>Tour</span>
                </span>
              </Link>
            </div>

            <div className="hidden xl:flex items-center absolute left-1/2 -translate-x-1/2 space-x-6">
              {/* Membership link — external portal, shown first */}
              <a
                href={membershipPortalUrl}
                target="_blank"
                rel="noopener noreferrer"
                className={`inline-flex items-center gap-1.5 text-sm font-semibold transition-all px-3 py-1.5 rounded-full ${
                  showSolid
                    ? "text-[#7a0f0f] bg-[#f5e6e6] hover:bg-[#ecdada]"
                    : "text-white bg-white/15 hover:bg-white/25 backdrop-blur-sm"
                }`}
              >
                <Crown className="w-3.5 h-3.5" />
                Membership
              </a>

              <Link href="/" className={linkClassName(isActive("/"))}>
                {t("home")}
              </Link>

              {/* Layanan dropdown */}
              <div className="relative" ref={servicesRef}>
                <button
                  type="button"
                  onClick={() => setIsServicesOpen((v) => !v)}
                  className={`flex items-center gap-1 ${linkClassName(isServicesActive)}`}
                >
                  {t("services")}
                  <ChevronDown className={`h-3.5 w-3.5 transition-transform ${isServicesOpen ? "rotate-180" : ""}`} />
                </button>

                {isServicesOpen && (
                  <div className="absolute top-full left-1/2 -translate-x-1/2 mt-3 w-56 rounded-xl bg-white shadow-xl border border-gray-100 overflow-hidden py-2 text-heading z-50">
                    {serviceLinks.map((link) => (
                      <Link
                        key={link.name}
                        href={link.href as any}
                        onClick={() => setIsServicesOpen(false)}
                        className={`block px-5 py-2.5 text-sm transition ${
                          isActive(link.href)
                            ? "text-merah-ranata font-semibold bg-red-50"
                            : "hover:bg-gray-50"
                        }`}
                      >
                        {link.name}
                      </Link>
                    ))}
                  </div>
                )}
              </div>

              {navLinks.slice(1).map((link) => (
                <Link
                  key={link.name}
                  href={link.href as any}
                  className={linkClassName(isActive(link.href))}
                >
                  {link.name}
                </Link>
              ))}
            </div>

            <div className="hidden xl:flex items-center space-x-4">
              <LanguageSwitcher showSolid={showSolid} />
              {session ? (
                <div className="flex items-center gap-3">
                  {session.user?.role === "admin" ? (
                    <NextLink
                      href="/admin"
                      className={`text-sm px-5 py-2 rounded-full transition ${
                        showSolid
                          ? "bg-slate-100 text-heading hover:bg-slate-200"
                          : "bg-white/10 text-white hover:bg-white/20 backdrop-blur-sm"
                      }`}
                    >
                      Admin Panel
                    </NextLink>
                  ) : (
                    <Link
                      href="/member"
                      className={`text-sm px-5 py-2 rounded-full transition ${
                        showSolid
                          ? "bg-slate-100 text-heading hover:bg-slate-200"
                          : "bg-white/10 text-white hover:bg-white/20 backdrop-blur-sm"
                      }`}
                    >
                      Member Area
                    </Link>
                  )}
                  <button
                    type="button"
                    onClick={() => signOut({ callbackUrl: "/" })}
                    className={`text-sm px-5 py-2 rounded-full transition ${
                      showSolid
                        ? "bg-merah-ranata text-white hover:bg-merah-hover"
                        : "bg-white text-heading hover:bg-gray-100"
                    }`}
                  >
                    Logout
                  </button>
                </div>
              ) : (
                <NextLink
                  href="/login"
                  className={`text-sm px-5 py-2 rounded-full transition ${
                    showSolid
                      ? "bg-merah-ranata text-white hover:bg-merah-hover"
                      : "bg-white text-heading hover:bg-gray-100"
                  }`}
                >
                  Masuk / Daftar
                </NextLink>
              )}
            </div>

            <div className="xl:hidden flex items-center gap-4">
              <LanguageSwitcher showSolid={showSolid} />
              <button
                onClick={() => setIsMobileMenuOpen(true)}
                className={`p-2 rounded-md ${
                  showSolid ? "text-heading hover:bg-gray-100" : "text-white hover:bg-white/20"
                }`}
              >
                <Menu className="h-6 w-6" />
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile Off-canvas Menu */}
      <div
        className={`fixed inset-0 z-[60] xl:hidden transition-opacity duration-300 ${
          isMobileMenuOpen ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none"
        }`}
      >
        <div
          className="absolute inset-0 bg-black/50"
          onClick={() => setIsMobileMenuOpen(false)}
        />

        <div
          className={`absolute top-0 right-0 bottom-0 w-[280px] bg-white text-heading shadow-xl transform transition-transform duration-300 ${
            isMobileMenuOpen ? "translate-x-0" : "translate-x-full"
          } flex flex-col`}
        >
          <div className="p-4 flex justify-end">
            <button
              onClick={() => setIsMobileMenuOpen(false)}
              className="p-2 rounded-md hover:bg-gray-100"
            >
              <X className="h-6 w-6" />
            </button>
          </div>

          <div className="flex-1 overflow-y-auto px-4 py-2 space-y-1">
            {/* Membership — mobile, shown first */}
            <a
              href={membershipPortalUrl}
              target="_blank"
              rel="noopener noreferrer"
              onClick={() => setIsMobileMenuOpen(false)}
              className="flex items-center justify-between px-4 py-3 rounded-lg text-base font-semibold text-[#7a0f0f] bg-[#f5e6e6] hover:bg-[#ecdada] transition"
            >
              <span className="flex items-center gap-2">
                <Crown className="w-4 h-4" />
                Membership
              </span>
              <span className="text-xs font-bold bg-[#7a0f0f] text-white px-2 py-0.5 rounded-full">Portal</span>
            </a>

            <Link
              href="/"
              onClick={() => setIsMobileMenuOpen(false)}
              className={`block px-4 py-3 rounded-lg text-base font-medium flex justify-between items-center transition ${
                isActive("/") ? "bg-red-50 text-merah-ranata" : "hover:bg-gray-50"
              }`}
            >
              {t("home")}
              {isActive("/") && <span className="w-1.5 h-1.5 rounded-full bg-merah-ranata"></span>}
            </Link>

            {/* Layanan — mobile collapsible group */}
            <div>
              <button
                type="button"
                onClick={() => setIsMobileServicesOpen((v) => !v)}
                className={`w-full flex items-center justify-between px-4 py-3 rounded-lg text-base font-medium transition ${
                  isServicesActive ? "bg-red-50 text-merah-ranata" : "hover:bg-gray-50"
                }`}
              >
                {t("services")}
                <ChevronDown className={`h-4 w-4 transition-transform ${isMobileServicesOpen ? "rotate-180" : ""}`} />
              </button>
              {isMobileServicesOpen && (
                <div className="pl-4 mt-1 space-y-1">
                  {serviceLinks.map((link) => (
                    <Link
                      key={link.name}
                      href={link.href as any}
                      onClick={() => setIsMobileMenuOpen(false)}
                      className={`block px-4 py-2.5 rounded-lg text-sm flex justify-between items-center transition ${
                        isActive(link.href)
                          ? "bg-red-50 text-merah-ranata font-semibold"
                          : "hover:bg-gray-50 text-body"
                      }`}
                    >
                      {link.name}
                      {isActive(link.href) && (
                        <span className="w-1.5 h-1.5 rounded-full bg-merah-ranata"></span>
                      )}
                    </Link>
                  ))}
                </div>
              )}
            </div>

            {navLinks.slice(1).map((link) => (
              <Link
                key={link.name}
                href={link.href as any}
                onClick={() => setIsMobileMenuOpen(false)}
                className={`block px-4 py-3 rounded-lg text-base font-medium flex justify-between items-center transition ${
                  isActive(link.href)
                    ? "bg-red-50 text-merah-ranata"
                    : "hover:bg-gray-50"
                }`}
              >
                {link.name}
                {isActive(link.href) && (
                  <span className="w-1.5 h-1.5 rounded-full bg-merah-ranata"></span>
                )}
              </Link>
            ))}
          </div>

          <div className="p-4 border-t border-gray-100">
            {session ? (
              <div className="space-y-2">
                {session.user?.role === "admin" ? (
                  <NextLink
                    href="/admin"
                    onClick={() => setIsMobileMenuOpen(false)}
                    className="block w-full text-center px-4 py-3 bg-slate-100 text-slate-800 rounded-lg font-medium hover:bg-slate-200 transition"
                  >
                    Admin Panel
                  </NextLink>
                ) : (
                  <Link
                    href="/member"
                    onClick={() => setIsMobileMenuOpen(false)}
                    className="block w-full text-center px-4 py-3 bg-slate-100 text-slate-800 rounded-lg font-medium hover:bg-slate-200 transition"
                  >
                    Member Area
                  </Link>
                )}
                <button
                  type="button"
                  onClick={() => {
                    setIsMobileMenuOpen(false);
                    signOut({ callbackUrl: "/" });
                  }}
                  className="block w-full text-center px-4 py-3 bg-merah-ranata text-white rounded-lg font-medium hover:bg-merah-hover transition"
                >
                  Logout
                </button>
              </div>
            ) : (
              <NextLink
                href="/login"
                onClick={() => setIsMobileMenuOpen(false)}
                className="block w-full text-center px-4 py-3 bg-merah-ranata text-white rounded-lg font-medium hover:bg-merah-hover transition"
              >
                Masuk / Daftar
              </NextLink>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
