"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import {
  Menu,
  X,
  Home,
  Box,
  Briefcase,
  Newspaper,
  Search,
  Globe,
  LogIn,
  ChevronDown,
  Video,
  Music,
  Image as ImageIcon,
  FileText,
} from "lucide-react";
import { fetchPublishedArticles } from "@/lib/articles-public";

const LANDING_SECTION_IDS = new Set(["products", "services"]);

function scrollToSectionId(id: string) {
  document
    .getElementById(id)
    ?.scrollIntoView({ behavior: "smooth", block: "start" });
}

export type LandingSiteNavProps = {
  /** GET form target for navbar search (e.g. `/news-services`). If omitted, search is display-only. */
  searchFormAction?: string;
  searchDefaultValue?: string;
  searchPlaceholder?: string;
  /** News hub pages: “Home” → `/news-services`, plus Konten submenu in drawer */
  newsHub?: boolean;
};

export default function LandingSiteNav({
  searchFormAction,
  searchDefaultValue = "",
  searchPlaceholder = "Search",
  newsHub = false,
}: LandingSiteNavProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [openKonten, setOpenKonten] = useState(false);
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [event, setEvent] = useState<any>(null);
  const [popular, setPopular] = useState<any[]>([]);

  useEffect(() => {
    const loadPopular = async () => {
      const res = await fetchPublishedArticles(
        {
          typeId: 1,
          limit: 3,
          page: 1,
          sortBy: "view_count",
          sort: "desc",
        },
        { mode: "client" },
      );

      setPopular(res?.items ?? []);
    };

    loadPopular();
  }, []);

  useEffect(() => {
    const loadEvent = async () => {
      const res = await fetchPublishedArticles(
        {
          typeId: 1,
          limit: 1,
          page: 1,
          sortBy: "created_at",
          sort: "desc",
        },
        { mode: "client" },
      );

      const firstItem = res?.items?.[0];
      if (firstItem) {
        setEvent(firstItem);
      }
    };

    loadEvent();
  }, []);

  useEffect(() => {
    if (pathname !== "/") return;
    const syncFromHash = () => {
      const raw = window.location.hash.replace(/^#/, "");
      if (!LANDING_SECTION_IDS.has(raw)) return;
      const el = document.getElementById(raw);
      if (!el) return;
      requestAnimationFrame(() =>
        el.scrollIntoView({ behavior: "smooth", block: "start" }),
      );
    };
    const t = window.setTimeout(syncFromHash, 0);
    window.addEventListener("hashchange", syncFromHash);
    return () => {
      window.clearTimeout(t);
      window.removeEventListener("hashchange", syncFromHash);
    };
  }, [pathname]);

  const homePath = newsHub ? "/news-services" : "/";

  const goHome = () => {
    setOpen(false);
    if (pathname === homePath) {
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      router.push(homePath);
    }
  };

  function MenuItem({
    icon,
    label,
    onClick,
  }: {
    icon: React.ReactNode;
    label: string;
    onClick?: () => void;
  }) {
    return (
      <div
        onClick={onClick}
        className="flex cursor-pointer items-center gap-3  border-white/20 pb-3 hover:opacity-80"
      >
        {icon}
        <span>{label}</span>
      </div>
    );
  }

  const searchField = (
    <div className="relative min-w-0 max-w-[min(100%,11rem)] flex-1 sm:max-w-none sm:flex-initial md:w-56 lg:w-64">
      <Search
        className="pointer-events-none absolute left-3.5 top-1/2 size-[18px] -translate-y-1/2 text-gray-400"
        aria-hidden
      />
      <input
        type="search"
        name="q"
        defaultValue={searchDefaultValue}
        placeholder={searchPlaceholder}
        className="w-full rounded-full border border-[#966314]/55 bg-white py-2 pl-10 pr-4 text-sm text-gray-900 placeholder:text-gray-400 outline-none focus-visible:ring-2 focus-visible:ring-[#966314]/30"
      />
    </div>
  );

  return (
    <>
      <nav
        className={`fixed top-0 left-0 right-0 z-100 w-full transition-all duration-300 ${
          open
            ? "bg-[#966314] text-white border-none"
            : "bg-white/95 text-gray-900 border-b border-gray-100"
        }`}
      >
        <div className="container mx-auto flex items-center justify-between gap-4 px-4 py-4 md:px-6">
          <Link href="/" className="shrink-0">
            <Image
              src="/image/qudo1.png"
              alt="Qudoco"
              width={140}
              height={56}
              className="h-12 w-auto md:h-14"
              priority
            />
          </Link>

          <div className="flex min-w-0 flex-1 items-center justify-end gap-3 md:gap-5">
            {searchFormAction ? (
              <form method="get" action={searchFormAction} className="contents">
                {searchField}
              </form>
            ) : (
              searchField
            )}

            <button
              type="button"
              className={`hidden items-center gap-2 text-sm  sm:flex ${
                open ? " text-white" : " text-black "
              }`}
            >
              <Globe
                className={`size-[18px] ${
                  open ? " text-white" : " text-black "
                }`}
                strokeWidth={1.75}
              />
              English
            </button>

            <span
              className="hidden h-5 w-px shrink-0 bg-gray-300 sm:block"
              aria-hidden
            />

            <button
              type="button"
              onClick={() => setOpen(true)}
              className={`flex items-center gap-2 text-sm font-semibold ${
                open ? " text-white" : " text-black "
              }`}
            >
              <Menu
                className={`size-5 ${open ? " text-white" : " text-black "}`}
                strokeWidth={2}
              />
              Menu
            </button>
          </div>
        </div>
      </nav>

      {open ? (
        <button
          type="button"
          aria-label="Close menu"
          className="fixed inset-0 z-[90] bg-black/40"
          onClick={() => setOpen(false)}
        />
      ) : null}

      <div
        className={`fixed top-[80px] left-0 right-0 bottom-0 z-100 bg-gradient-to-bl from-[#966314] to-[#b07a1c] text-white transition-all duration-300 ${
          open ? "opacity-100 visible" : "opacity-0 invisible"
        }`}
      >
        <div className="flex h-full flex-col p-10">
          {/* TOP BAR */}
          <div className="flex justify-end items-end mb-10">
            <button onClick={() => setOpen(false)}>
              <X size={24} />
            </button>
          </div>

          {/* MENU */}
          <div className="grid grid-cols-2 gap-16 flex-1">
            <div className="flex flex-col gap-6 text-2xl font-semibold">
              <MenuItem
                icon={<Home size={22} />}
                label="Home"
                onClick={goHome}
              />

              <MenuItem
                icon={<Box size={22} />}
                label="Product"
                onClick={() => setActiveMenu("product")}
              />

              <MenuItem
                icon={<Briefcase size={22} />}
                label="Services"
                onClick={() => setActiveMenu("services")}
              />

              <MenuItem
                icon={<Newspaper size={22} />}
                label="News and Services"
                onClick={() => setActiveMenu("news&services")}
              />

              <MenuItem
                icon={<LogIn size={22} />}
                label="Login"
                onClick={() => router.push("/auth")}
              />
            </div>
            <div className="flex flex-col justify-start pt-4">
              {activeMenu === "product" && (
                <div className="space-y-4">
                  <p className="text-sm opacity-70">Product</p>

                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    MediaHUB Content Aggregator
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Multipool Reputation Management
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    PR Room Opinion Management
                  </p>
                </div>
              )}

              {activeMenu === "services" && (
                <div className="space-y-4">
                  <p className="text-sm opacity-70">Services</p>

                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Artifintel
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Produksi Video Animasi
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Reelithic
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Qudoin
                  </p>
                  <p className="text-lg font-semibold cursor-pointer hover:underline">
                    Talkshow Ai
                  </p>
                </div>
              )}
              {activeMenu === "news&services" && (
                <div className="space-y-4">
                  <p className="text-sm opacity-70">News & Services</p>
                  <Link
                    href="/news-services"
                    className="block rounded-md px-2 py-2 hover:bg-white/10"
                    onClick={() => setOpen(false)}
                  >
                    <p className="text-lg font-semibold cursor-pointer hover:underline">
                      Homepage News
                    </p>
                  </Link>
                  <Link
                    href="/video/filter"
                    className="block rounded-md px-2 py-2 hover:bg-white/10"
                    onClick={() => setOpen(false)}
                  >
                    <p className="text-lg font-semibold cursor-pointer hover:underline">
                      Audio Visual
                    </p>
                  </Link>
                  <Link
                    href="/audio/filter"
                    className="block rounded-md px-2 py-2 hover:bg-white/10"
                    onClick={() => setOpen(false)}
                  >
                    <p className="text-lg font-semibold cursor-pointer hover:underline">
                      Audio
                    </p>
                  </Link>
                  <Link
                    href="/image/filter"
                    className="block rounded-md px-2 py-2 hover:bg-white/10"
                    onClick={() => setOpen(false)}
                  >
                    <p className="text-lg font-semibold cursor-pointer hover:underline">
                      Foto
                    </p>
                  </Link>
                  <Link
                    href="/document/filter"
                    className="block rounded-md px-2 py-2 hover:bg-white/10"
                    onClick={() => setOpen(false)}
                  >
                    <p className="text-lg font-semibold cursor-pointer hover:underline">
                      Teks
                    </p>
                  </Link>
                </div>
              )}
            </div>
          </div>
          <div className="mt-auto grid grid-cols-2 gap-10 pt-10">
            {/* POPULAR */}
            <ul className="space-y-3 text-sm">
              <p className="text-[16px] opacity-70 mb-3">POPULAR PAGES</p>
              {popular.length > 0 ? (
                popular.map((item) => (
                  <li key={item.id}>
                    <Link
                      href={`/news/${item.slug}`}
                      onClick={() => setOpen(false)}
                      className="hover:underline line-clamp-2 text-sm"
                    >
                      {item.title}
                    </Link>
                  </li>
                ))
              ) : (
                <li className="opacity-50">Loading...</li>
              )}
            </ul>

            {/* EVENT */}
            <div>
              <p className="text-sm opacity-70 mb-3">Upcoming Event</p>

              {event ? (
                <div className="bg-white/10 rounded-xl p-4 flex gap-4 items-center">
                  {/* IMAGE */}
                  <div className="w-20 h-20 rounded-md overflow-hidden bg-white/20 shrink-0">
                    {event.thumbnailUrl ? (
                      <Image
                        src={event.thumbnailUrl}
                        alt={event.title}
                        width={80}
                        height={80}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full bg-white/20" />
                    )}
                  </div>

                  {/* TEXT */}
                  <div className="flex flex-col">
                    <p className="font-semibold line-clamp-2">{event.title}</p>

                    <p className="text-xs opacity-70 line-clamp-2">
                      {event.description?.slice(0, 120)}...
                    </p>
                  </div>
                </div>
              ) : (
                <p className="text-xs opacity-50">Loading...</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function MenuItem({ icon, label }: { icon: React.ReactNode; label: string }) {
  return (
    <div className="flex cursor-pointer items-center justify-between border-b border-white/20 pb-3">
      <span>{label}</span>
      {icon}
    </div>
  );
}
