"use client";

import Image from "next/image";
import Link from "next/link";
import { useState, useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { publicConfigApi } from "@/lib/api/public";
import { buildImageUrl } from "@/lib/utils/image";
import type { Config } from "@/types/config";

export default function Navbar() {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [config, setConfig] = useState<Config | null>(null);
  const pathname = usePathname();
  const router = useRouter();
  const isHomePage = pathname === "/";

  useEffect(() => {
    publicConfigApi.getConfig().then((res) => setConfig(res.data)).catch(() => { });
  }, []);

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener("scroll", handleScroll);
    handleScroll();
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const logoSrc = config?.logo ? buildImageUrl(config.logo) : "/logoptbmmki.svg";
  const siteName = config?.site_name ?? "PTBMMKI";
  const siteDescription =
    config?.site_description ?? "Perhimpunan Tim Bantuan Medis Mahasiswa\nKedokteran Indonesia";

  const getNavbarStyle = () => {
    if (isHomePage && !scrolled && !open) return "bg-transparent text-white";
    return `
      !bg-[#E67817]
      lg:!bg-[rgba(230,120,23,0.8)]
      lg:backdrop-blur-lg
      lg:backdrop-saturate-150
      shadow-lg
      text-white
      z-999
    `;
  };

  const navigateToSection = (sectionId: string) => {
    if (pathname !== "/") {
      router.push(`/#${sectionId}`);
    } else {
      window.history.pushState(null, "", `/#${sectionId}`);
      const element = document.getElementById(sectionId);
      if (element) {
        const offsetPosition =
          element.getBoundingClientRect().top + window.pageYOffset - 80;
        window.scrollTo({ top: offsetPosition, behavior: "auto" });
      }
    }
    setOpen(false);
  };

  const isSectionActive = (sectionId: string) => {
    if (!isHomePage || typeof window === "undefined") return false;
    return window.location.hash === `#${sectionId}`;
  };

  const navLinkClass = (sectionId: string) =>
    `relative inline-block pb-1 transition-all duration-300 cursor-pointer ${isSectionActive(sectionId) ? "font-semibold" : "text-gray-200"
    } hover:text-white hover:after:absolute hover:after:bottom-0 hover:after:left-0 hover:after:content-[''] hover:after:h-0.5 hover:after:bg-white hover:after:rounded-2xl hover:after:transition-all hover:after:duration-300 hover:after:w-0 hover:hover:after:w-full`;

  const mobileLinkClass = (sectionId: string) =>
    `relative pb-1 transition duration-200 inline-block cursor-pointer ${isSectionActive(sectionId) ? "text-white font-semibold" : "text-gray-200"
    } hover:text-white`;

  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash;
      if (hash) {
        const el = document.getElementById(hash.substring(1));
        if (el) {
          const offsetPosition = el.getBoundingClientRect().top + window.pageYOffset - 80;
          window.scrollTo({ top: offsetPosition, behavior: "auto" });
        }
      }
    };
    window.addEventListener("hashchange", handleHashChange);
    if (window.location.hash) setTimeout(handleHashChange, 100);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, []);

  const navLinks = [
    { id: "hero", label: "Beranda" },
    { id: "tentang-kami", label: "Tentang Kami" },
    { id: "kepemimpinan", label: "Profil Organisasi" },
    { id: "berita", label: "Berita dan Pengumuman" },
    { id: "kontak", label: "Kontak Kami" },
  ];

  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${getNavbarStyle()}`}>
      <div className="w-full mx-auto px-6 md:px-20 lg:px-36 py-4 md:py-6 flex items-center justify-between">

        <div className="flex items-center gap-4">
          <Link href="/">
            <Image
              src={logoSrc}
              alt={`Logo ${siteName}`}
              width={70}
              height={70}
              className={`transition-all duration-300 ${isHomePage && !scrolled ? "opacity-90" : "opacity-100"
                } cursor-pointer`}
              unoptimized
            />
          </Link>
          <div className="leading-tight">
            <h1 className="text-3xl font-extrabold tracking-wide drop-shadow-sm">
              {siteName}
            </h1>
            <p className="text-[8px] md:text-xs font-medium sm:block drop-shadow-sm">
              {siteDescription.split("\n").map((line, i) => (
                <span key={i}>
                  {line}
                  {i < siteDescription.split("\n").length - 1 && <br />}
                </span>
              ))}
            </p>
          </div>
        </div>

        <nav className="hidden lg:flex gap-6 text-md">
          {navLinks.map((link) => (
            <Link
              key={link.id}
              href={`/#${link.id}`}
              onClick={(e) => { e.preventDefault(); navigateToSection(link.id); }}
              className={navLinkClass(link.id)}
            >
              {link.label}
            </Link>
          ))}
        </nav>

        <button
          className="lg:hidden flex flex-col gap-1 cursor-pointer"
          onClick={() => setOpen(!open)}
          aria-label="Toggle menu"
        >
          <span className={`w-6 h-[2px] bg-white transition-all duration-300 ${open ? "rotate-45 translate-y-1.5" : ""}`} />
          <span className={`w-6 h-[2px] bg-white transition-all duration-300 ${open ? "opacity-0" : ""}`} />
          <span className={`w-6 h-[2px] bg-white transition-all duration-300 ${open ? "-rotate-45 -translate-y-1.5" : ""}`} />
        </button>
      </div>

      {open && (
        <nav className="lg:hidden px-6 pt-2 pb-6 md:px-36 bg-brand">
          <div className="flex flex-col gap-4 text-md">
            {navLinks.map((link) => (
              <Link
                key={link.id}
                href={`/#${link.id}`}
                onClick={(e) => { e.preventDefault(); navigateToSection(link.id); }}
                className={mobileLinkClass(link.id)}
              >
                {link.label}
              </Link>
            ))}
          </div>
        </nav>
      )}
    </header>
  );
}