"use client";

import { useState, useEffect } from "react";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import Image from "next/image";
import { Menu, ChevronDown } from "lucide-react";
import { Button } from "../ui/button";
import Cookies from "js-cookie";
import { Card } from "../ui/card";
import { Input } from "../ui/input";
import { usePathname, useRouter } from "next/navigation";
import { Link } from "@/i18n/routing";
import { DynamicLogoTenant } from "./dynamic-logo-tenant";
import { useTranslations } from "next-intl";
import LocalSwitcher from "../partials/header/locale-switcher";
import ThemeSwitcher from "../partials/header/theme-switcher";
import { RevealT } from "../ui/RevealT";

export default function Navbar() {
  const t = useTranslations("Navbar");
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isDropdownOpen, setDropdownOpen] = useState(false);
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const pathname = usePathname();
  const router = useRouter();

  const NAV_ITEMS = [
    { label: t("home"), href: "/" },
    { label: t("forYou"), href: "/for-you" },
    { label: t("following"), href: "/auth" },
    { label: t("publication"), href: "/publikasi" },
    { label: t("schedule"), href: "/schedule" },
  ];

  const PUBLIKASI_SUBMENU = [
    { label: "K/L", href: "/in/publication/kl" },
    { label: "BUMN", href: "/in/publication/bumn" },
    { label: t("localGov"), href: "/in/publication/pemerintah-daerah" },
  ];

  // 🔍 Fungsi cek login
  const checkLoginStatus = () => {
    const roleId = getCookiesDecrypt("urie");
    const fullname = Cookies.get("ufne");
    return roleId && fullname ? true : false;
  };

  useEffect(() => {
    setIsLoggedIn(checkLoginStatus());
  }, []);

  const filteredNavItems = isLoggedIn
    ? NAV_ITEMS.filter((item) => item.label !== t("following"))
    : NAV_ITEMS;

  // 🚪 Fungsi logout
  const handleLogout = () => {
    Object.keys(Cookies.get()).forEach((cookieName) => {
      Cookies.remove(cookieName, { path: "/" });
      Cookies.remove(cookieName, {
        path: "",
        domain: window.location.hostname,
      });
      Cookies.remove(cookieName, {
        path: "/",
        domain: window.location.hostname,
      });
    });
    setIsLoggedIn(false);
    setShowProfileMenu(false);
    window.location.href = "/";
  };

  const username = Cookies.get("username");
  const fullname = Cookies.get("ufne");

  return (
    <RevealT>
      <header className="relative max-w-[1400px] mx-auto flex items-center justify-between px-4 py-3 border-b bg-white dark:bg-default-50 z-50">
        <div className="flex flex-row items-center justify-between space-x-4 z-10">
          <Menu
            className="w-6 h-6 cursor-pointer"
            onClick={() => setIsSidebarOpen(true)}
          />

          <Link href="/" className="relative w-32 h-20">
            <Image
              src="/assets/logo1.png"
              alt="Logo"
              fill
              className="object-contain"
            />
          </Link>

          <DynamicLogoTenant />

          <div className="hidden custom-lg-button:flex items-end">
            <ThemeSwitcher />
          </div>
        </div>

        {/* 🌐 NAV MENU */}
        <nav className="absolute left-1/2 -translate-x-1/2 hidden md:flex space-x-3 lg:space-x-8 text-sm font-medium">
          {filteredNavItems.map((item) => {
            const isActive = pathname === item.href;

            // 🔹 Pengecekan khusus untuk "Untuk Anda"
            const handleClick = (e: React.MouseEvent) => {
              if (item.label === t("forYou")) {
                e.preventDefault();
                if (!checkLoginStatus()) {
                  router.push("/auth");
                } else {
                  router.push("/in/for-you");
                }
              }
            };

            return (
              <div key={item.label} className="relative">
                {item.label === t("publication") ? (
                  <>
                    <button
                      onClick={() => setDropdownOpen(!isDropdownOpen)}
                      className={cn(
                        "relative text-gray-500 dark:text-white dark:hover:text-slate-300 hover:text-black transition-colors",
                        isDropdownOpen ||
                          pathname.startsWith("/public/publication")
                          ? "text-black"
                          : "",
                      )}
                    >
                      {item.label}
                      <span
                        className={cn(
                          "absolute -bottom-1 left-1/2 -translate-x-1/2 w-6 h-[3px] bg-red-800 rounded transition-all",
                          isDropdownOpen ||
                            pathname.startsWith("/public/publication")
                            ? "opacity-100"
                            : "opacity-0",
                        )}
                      />
                    </button>

                    {isDropdownOpen && (
                      <div className="absolute top-full mt-2 w-48 bg-white border rounded shadow z-50">
                        {PUBLIKASI_SUBMENU.map((sub) => (
                          <Link
                            key={sub.label}
                            href={sub.href}
                            className="block px-4 py-2 text-sm hover:bg-gray-100 text-gray-700 dark:text-white"
                          >
                            {sub.label}
                          </Link>
                        ))}
                      </div>
                    )}
                  </>
                ) : (
                  <Link
                    href={item.href}
                    onClick={handleClick}
                    className={cn(
                      "relative text-gray-500 dark:text-white dark:hover:text-slate-300 hover:text-black transition-colors",
                      isActive && "text-black",
                    )}
                  >
                    {item.label}
                    {isActive && (
                      <span className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-6 h-[3px] bg-red-800 rounded" />
                    )}
                  </Link>
                )}
              </div>
            );
          })}
        </nav>

        {/* 🔹 PROFILE / LOGIN SECTION */}
        <nav className="hidden md:flex items-center gap-3 z-10 relative">
          {!isLoggedIn ? (
            <>
              <Link href="/auth/register">
                <Button className="bg-transparent border text-black hover:bg-red-600 hover:text-white cursor-pointer">
                  {t("register")}{" "}
                </Button>
              </Link>
              <Link href="/auth">
                <Button className="bg-red-700 text-white cursor-pointer hover:bg-white hover:border hover:border-red-700 hover:text-red-700">
                  {t("login")}
                </Button>
              </Link>
            </>
          ) : (
            <div className="relative">
              <button
                onClick={() => setShowProfileMenu((prev) => !prev)}
                className="flex items-center gap-2 border-2 py-1 px-3 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-700 cursor-pointer"
              >
                <div className="w-9 h-9 rounded-full overflow-hidden border">
                  <Image
                    src="/avatar-profile.png"
                    alt={username || "User avatar"}
                    width={36}
                    height={36}
                    className="object-cover"
                  />
                </div>
                <span className="text-sm font-medium text-gray-800 dark:text-white">
                  {fullname}
                </span>
                <ChevronDown className="w-4 h-4 text-gray-600" />
              </button>

              {showProfileMenu && (
                <div className="absolute right-0 mt-2 w-40 bg-white dark:bg-black border rounded shadow z-50 ">
                  <Link
                    href="/admin/dashboard"
                    className="flex flex-row items-center  text-left px-4 py-2 hover:bg-gray-300 dark:hover:bg-gray-700 text-gray-700 dark:text-white"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                    >
                      <path
                        fill="currentColor"
                        d="M14 21a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1zM4 13a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1zm5-2V5H5v6zM4 21a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1zm1-2h4v-2H5zm10 0h4v-6h-4zM13 4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1h-6a1 1 0 0 1-1-1zm2 1v2h4V5z"
                      />
                    </svg>
                    &nbsp;Dashboard
                  </Link>

                  <button
                    onClick={handleLogout}
                    className="w-full flex flex-row text-left px-4 py-2 hover:bg-gray-300 text-gray-700 dark:text-white cursor-pointer"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                    >
                      <g
                        fill="none"
                        stroke="currentColor"
                        strokeLinecap="round"
                        strokeWidth="1.5"
                      >
                        <path
                          strokeLinejoin="round"
                          d="M13.477 21.245H8.34a4.92 4.92 0 0 1-5.136-4.623V7.378A4.92 4.92 0 0 1 8.34 2.755h5.136"
                        />
                        <path strokeMiterlimit="10" d="M20.795 12H7.442" />
                        <path
                          strokeLinejoin="round"
                          d="m16.083 17.136l4.404-4.404a1.04 1.04 0 0 0 0-1.464l-4.404-4.404"
                        />
                      </g>
                    </svg>
                    &nbsp;{t("logout")}
                  </button>
                </div>
              )}
            </div>
          )}
        </nav>

        {/* 📱 SIDEBAR MOBILE */}
        {isSidebarOpen && (
          <div className="fixed inset-0 z-50 flex">
            <div className="w-80 bg-white p-6 space-y-6 shadow-lg relative h-full overflow-y-auto">
              <button
                onClick={() => setIsSidebarOpen(false)}
                className="absolute top-4 right-4 text-gray-600"
              >
                ✕
              </button>

              <div className="mt-10">
                <h3 className="text-[16px] font-bold text-gray-700 mb-2">
                  {t("language")}
                </h3>
                {/* button language */}
                <div className={`relative text-left border w-fit rounded-lg`}>
                  <LocalSwitcher />
                </div>
                {/* <div className="space-y-5 ml-3">
                <button className="flex items-center gap-2 text-sm text-gray-800">
                  <Image src={"/Flag.svg"} width={24} height={24} alt="flag" />
                  English
                </button>
                <button className="flex items-center gap-2 text-sm text-gray-800">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 36 36"
                  >
                    <path
                      fill="#dc1f26"
                      d="M32 5H4a4 4 0 0 0-4 4v9h36V9a4 4 0 0 0-4-4"
                    />
                    <path
                      fill="#eee"
                      d="M36 27a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4v-9h36z"
                    />
                  </svg>{" "}
                  Bahasa Indonesia
                </button>
              </div> */}
              </div>

              <div>
                <h3 className="text-[16px] font-bold text-gray-700 dark:text-white mb-2">
                  {t("features")}
                </h3>
                <div className="space-y-5 ml-3">
                  {NAV_ITEMS.map((item) => (
                    <button
                      key={item.label}
                      onClick={() => {
                        if (item.label === t("forYou")) {
                          if (!checkLoginStatus()) {
                            router.push("/auth");
                          } else {
                            router.push("/for-you");
                          }
                        } else {
                          router.push(item.href);
                        }
                        setIsSidebarOpen(false);
                      }}
                      className="block text-[15px] text-gray-800 dark:text-white text-left w-full"
                    >
                      {item.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="space-y-5 text-[16px] font-bold">
                <Link
                  href="/about"
                  className="block text-black dark:text-white"
                >
                  {t("about")}
                </Link>
                <Link
                  href="/advertising"
                  className="block text-black dark:text-white"
                >
                  {t("advertising")}
                </Link>
                <Link
                  href="/contact"
                  className="block text-black dark:text-white"
                >
                  {t("contact")}
                </Link>

                {!isLoggedIn ? (
                  <>
                    <Link
                      href="/auth"
                      className="block text-lg text-gray-800 dark:text-white"
                    >
                      {t("login")}
                    </Link>
                    <Link
                      href="/auth/register"
                      className="block text-lg text-gray-800 dark:text-white"
                    >
                      {t("register")}
                    </Link>
                  </>
                ) : (
                  <button
                    onClick={handleLogout}
                    className="block text-left w-full text-lg text-red-600 hover:underline"
                  >
                    {t("logout")}
                  </button>
                )}
              </div>

              <Card className="rounded-none p-4">
                <h2 className="text-[#C6A455] text-center text-lg font-semibold mb-2">
                  {t("subscribeTitle")}
                </h2>
                <Input type="email" placeholder={t("subscribePlaceholder")} />
                <Button className="bg-[#C6A455] mt-2">
                  {t("subscribeButton")}
                </Button>
              </Card>
            </div>

            <div
              className="flex-1 bg-black/50"
              onClick={() => setIsSidebarOpen(false)}
            />
          </div>
        )}
      </header>
    </RevealT>
  );
}
