"use client";

import { useState, useEffect } from "react";
import { cn, getCookiesDecrypt } from "@/lib/utils";
import Image from "next/image";
import Link from "next/link";
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 } from "next/navigation";

const NAV_ITEMS = [
  { label: "Beranda", href: "/" },
  { label: "Untuk Anda", href: "/public/for-you" },
  { label: "Mengikuti", href: "/auth" },
  { label: "Publikasi", href: "/publikasi" },
  { label: "Jadwal", href: "/public/schedule" },
];

const PUBLIKASI_SUBMENU = [
  { label: "K/L", href: "/public/publication/kl" },
  { label: "BUMN", href: "/public/publication/bumn" },
  { label: "Pemerintah Daerah", href: "/public/publication/pemerintah-daerah" },
];

export default function Navbar() {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  const [user, setUser] = useState<{
    id: number;
    name: string;
    avatar: string;
  } | null>(null);

  const [isDropdownOpen, setDropdownOpen] = useState(false);
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const pathname = usePathname();

  useEffect(() => {
    const roleId = getCookiesDecrypt("urie");
    console.log("roleId", roleId);

    switch (roleId) {
      case "3":
        setUser({
          id: 3,
          name: "Mabes Polri - Approver",
          avatar: "/contributor.png",
        });
        break;

      case "7":
        setUser({
          id: 7,
          name: "DivHumas - RoMulmed - BagDise",
          avatar: "/contributor.png",
        });
        break;

      case "6":
        setUser({
          id: 11,
          name: "jurnalis-kompas1",
          avatar: "/contributor.png",
        });
        break;

      default:
        setUser(null);
    }
  }, []);

  const isLoggedIn = user !== null;

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

  const handleLogout = () => {
    Object.keys(Cookies.get()).forEach((cookieName) => {
      Cookies.remove(cookieName);
    });

    window.location.href = "/";

    setUser(null);
    setShowProfileMenu(false);
  };

  return (
    <header className="relative max-w-[1400px] mx-auto flex items-center justify-between px-4 py-3 border-b bg-white z-50">
      <div className="flex flex-row items-center justify-between space-x-4 z-10">
        <div className="relative w-32 h-20">
          <Image
            src="/assets/logo1.png"
            alt="Logo"
            fill
            className="object-contain"
          />
        </div>{" "}
        <Menu
          className="w-6 h-6 cursor-pointer"
          onClick={() => setIsSidebarOpen(true)}
        />
      </div>

      <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;

          return (
            <div key={item.label} className="relative">
              {item.label === "Publikasi" ? (
                <>
                  <button
                    onClick={() => setDropdownOpen(!isDropdownOpen)}
                    className={cn(
                      "relative text-gray-500 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"
                        >
                          {sub.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </>
              ) : (
                <Link
                  href={item.href}
                  className={cn(
                    "relative text-gray-500 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>
      <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">
                Daftar
              </Button>
            </Link>
            <Link href="/auth">
              <Button className="bg-red-700 text-white">Masuk</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-50"
            >
              <div className="w-9 h-9 rounded-full overflow-hidden border">
                <Image
                  src={user.avatar}
                  alt={user.name}
                  width={36}
                  height={36}
                  className="object-cover"
                />
              </div>
              <span className="text-sm font-medium text-gray-800">
                {user.name}
              </span>
              <ChevronDown className="w-4 h-4 text-gray-600" />
            </button>

            {showProfileMenu && (
              <div className="absolute right-0 mt-2 w-40 bg-white border rounded shadow z-50">
                <button
                  onClick={handleLogout}
                  className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 text-gray-700"
                >
                  Logout
                </button>
              </div>
            )}
          </div>
        )}
      </nav>

      {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">
                Bahasa
              </h3>
              <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 mb-2">
                Fitur
              </h3>
              <div className="space-y-5 ml-3">
                {NAV_ITEMS.map((item) => (
                  <Link
                    key={item.label}
                    href={item.href}
                    className="block text-[15px] text-gray-800"
                    onClick={() => setIsSidebarOpen(false)}
                  >
                    {item.label}
                  </Link>
                ))}
              </div>
            </div>

            <div className="space-y-5 text-[16px] font-bold">
              <Link
                href="/about"
                className="block text-black  text-[16px] font-bold"
              >
                Tentang Kami
              </Link>
              <Link
                href="/advertising"
                className="block  text-[16px] font-bold  text-black"
              >
                Advertising
              </Link>
              <Link
                href="/contact"
                className="block  text-[16px] font-bold  text-black"
              >
                Kontak Kami
              </Link>
              {!isLoggedIn ? (
                <>
                  <Link href="/auth" className="block text-lg text-gray-800">
                    Login
                  </Link>
                  <Link
                    href="/auth/register"
                    className="block text-lg text-gray-800"
                  >
                    Daftar
                  </Link>
                </>
              ) : (
                <button
                  onClick={handleLogout}
                  className="block text-left w-full text-lg text-red-600 hover:underline"
                >
                  Logout
                </button>
              )}
            </div>
            <Card className="rounded-none p-4">
              <h2 className="text-[#C6A455] text-center text-lg font-semibold">
                Subscribe to Our Newsletter
              </h2>
              <Input type="email" placeholder="Your email address" />
              <Button className="bg-[#C6A455]">Subscribe</Button>
            </Card>
          </div>

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