"use client";

import { memo, useState, useEffect, useRef } from "react";
import { Link, usePathname, useTranslation } from "@/i18n/navigation";
import { getStoredUserEmail, pbLogout } from "@/app/lib/pocketbase";
import ThemeToggle from "./ThemeToggle";

interface MenuItem {
  labelKey: string;
  href: string;
  icon: string;
  new?: boolean;
  ad?: boolean;
}

interface MenuSection {
  titleKey: string;
  items: MenuItem[];
}

export default memo(function SiteMenu({
  isOpen,
  onClose,
  onLoginClick,
}: {
  isOpen: boolean;
  onClose: () => void;
  onLoginClick: () => void;
}) {
  const { t } = useTranslation("menu");
  const pathname = usePathname();
  const ref = useRef<HTMLDivElement>(null);
  const [search, setSearch] = useState("");
  const [userEmail, setUserEmail] = useState<string | null>(null);

  useEffect(() => {
    setUserEmail(getStoredUserEmail());
  }, []);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("keydown", handleEscape);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen, onClose]);

  const sections: MenuSection[] = [
    {
      titleKey: "community",
      items: [
        { labelKey: "dating", href: "/dating", icon: "❤️" },
        { labelKey: "chat", href: "/join", icon: "💬" },
        { labelKey: "hostMeetup", href: "/meetups", icon: "🎤", new: true },
        { labelKey: "friendFinder", href: "/dating", icon: "💛" },
        { labelKey: "membersMap", href: "#", icon: "🌐" },
        { labelKey: "attendMeetup", href: "/meetups", icon: "🍹" },
      ],
    },
    {
      titleKey: "tools",
      items: [
        { labelKey: "explore", href: "/", icon: "📍" },
        { labelKey: "nextStop", href: "/dashboard", icon: "🗺️" },
        { labelKey: "climateFinder", href: "/tools", icon: "🌤️" },
        { labelKey: "fireCalculator", href: "/tools", icon: "🌱" },
        { labelKey: "aiAssistant", href: "/ai", icon: "🤖", new: true },
        { labelKey: "yearInReview", href: "/report", icon: "🥂" },
        { labelKey: "nomadStats", href: "/report", icon: "📊", new: true },
        { labelKey: "gigBoard", href: "/gigs", icon: "💰" },
        { labelKey: "costCalculator", href: "/tools", icon: "💱" },
      ],
    },
    {
      titleKey: "help",
      items: [
        { labelKey: "ideasBugs", href: "#", icon: "💡" },
        { labelKey: "faq", href: "#", icon: "🆘" },
        { labelKey: "terms", href: "#", icon: "📄" },
        { labelKey: "changelog", href: "#", icon: "🚀" },
      ],
    },
    {
      titleKey: "other",
      items: [
        { labelKey: "remoteJobs", href: "#", icon: "💼" },
        { labelKey: "coworking", href: "#", icon: "🏢" },
      ],
    },
  ];

  const profileItems: MenuItem[] = [
    { labelKey: "yourProfile", href: "/join", icon: "👤" },
    { labelKey: "settings", href: "/join", icon: "⚙️" },
    { labelKey: "favorites", href: "/", icon: "❤️" },
    { labelKey: "pricing", href: "/pricing", icon: "👑" },
    { labelKey: "nomadInsurance", href: "#", icon: "🛡️", ad: true },
  ];

  const filteredSections = sections.map((sec) => ({
    ...sec,
    items: search
      ? sec.items.filter((i) =>
          t(i.labelKey).toLowerCase().includes(search.toLowerCase())
        )
      : sec.items,
  })).filter((sec) => sec.items.length > 0);

  if (!isOpen) return null;

  return (
    <>
      <div className="fixed inset-0 z-40 bg-black/20 backdrop-blur-sm md:bg-transparent md:backdrop-blur-none" aria-hidden />
      <div
        ref={ref}
        className="fixed left-4 right-4 top-20 md:left-auto md:right-4 md:top-16 md:w-[480px] z-50 rounded-2xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-2xl overflow-hidden"
      >
        {/* Header */}
        <div className="p-4 border-b border-gray-100 dark:border-gray-800 space-y-3">
          <div className="flex items-center gap-2">
            {userEmail ? (
              <div className="flex items-center gap-2 flex-1 min-w-0">
                <div className="w-9 h-9 rounded-full bg-gradient-to-br from-[#ff4d4f] to-orange-500 flex items-center justify-center text-white text-sm font-bold shrink-0">
                  {userEmail[0].toUpperCase()}
                </div>
                <span className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                  {userEmail}
                </span>
              </div>
            ) : (
              <button
                onClick={onLoginClick}
                className="px-4 py-2 rounded-lg bg-[#ff4d4f] text-white text-sm font-medium hover:bg-[#ff3333] transition-colors"
              >
                {t("login")}
              </button>
            )}
            <Link
              href="/dashboard"
              onClick={onClose}
              className="px-4 py-2 rounded-lg bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 text-sm font-medium hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
            >
              {t("filters")}
            </Link>
            <Link
              href="/join"
              onClick={onClose}
              className="w-9 h-9 rounded-full bg-[#ff4d4f] text-white flex items-center justify-center hover:bg-[#ff3333] transition-colors shrink-0"
              aria-label={t("add")}
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
            </Link>
          </div>
          <div className="relative">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={t("searchPlaceholder")}
              className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 text-sm focus:outline-none focus:ring-2 focus:ring-[#ff4d4f]/20 focus:border-[#ff4d4f]"
            />
          </div>
        </div>

        {/* Profile + Dark mode */}
        <div className="px-4 py-3 border-b border-gray-100 dark:border-gray-800 flex flex-wrap items-center gap-2">
          {profileItems.map((item) => (
            <Link
              key={item.labelKey}
              href={item.href}
              onClick={onClose}
              className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
            >
              <span>{item.icon}</span>
              <span>{t(item.labelKey)}</span>
            </Link>
          ))}
          <div className="ml-auto flex items-center gap-2">
            <span className="text-xs text-gray-500 dark:text-gray-400">{t("darkMode")}</span>
            <ThemeToggle />
          </div>
        </div>

        {/* Sections */}
        <div className="max-h-[60vh] overflow-y-auto p-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {filteredSections.map((section) => (
              <div key={section.titleKey}>
                <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 dark:text-gray-500 mb-3">
                  {t(section.titleKey)}
                </h3>
                <ul className="space-y-1">
                  {section.items.map((item) => (
                    <li key={item.labelKey}>
                      <Link
                        href={item.href}
                        onClick={onClose}
                        className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
                          item.href !== "#" && (pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href)))
                            ? "bg-[#ff4d4f]/10 text-[#ff4d4f]"
                            : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800"
                        }`}
                      >
                        <span className="w-5 text-center">{item.icon}</span>
                        <span className="flex-1">{t(item.labelKey)}</span>
                        {item.new && (
                          <span className="px-2 py-0.5 rounded-full bg-[#ff4d4f] text-white text-[10px] font-medium">
                            NEW
                          </span>
                        )}
                        {item.ad && (
                          <span className="px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-[10px] text-gray-500">
                            Ad
                          </span>
                        )}
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        {/* Footer */}
        {userEmail && (
          <div className="p-4 border-t border-gray-100 dark:border-gray-800">
            <button
              onClick={() => {
                pbLogout();
                onClose();
              }}
              className="flex items-center gap-2 w-full px-3 py-2 rounded-lg text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
            >
              <span>🚪</span>
              <span>{t("logout")}</span>
            </button>
          </div>
        )}
      </div>
    </>
  );
});
