"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { LogoMark } from "@/components/brand/LogoMark";
import { FairyLights } from "@/components/layout/FairyLights";
import { FavoritesPanel } from "@/components/layout/navbar/FavoritesPanel";
import { CalendarPanel } from "@/components/layout/navbar/CalendarPanel";
import { ProfilePanel } from "@/components/layout/navbar/ProfilePanel";
import { SearchPopover } from "@/components/layout/navbar/SearchPopover";
import { MobileMenu } from "@/components/layout/MobileMenu";
import { NavLink } from "@/components/navigation/NavLink";
import {
  AUTHENTICATED_AUTH_ACTIONS,
  AUTHENTICATED_NAV,
  PUBLIC_AUTH_ACTIONS,
  PUBLIC_NAV,
} from "@/config/navigation.config";
import { ROUTES } from "@/config/routes.config";

export interface NavbarUser {
  id: string;
  name: string;
  email: string;
  avatar: string | null;
  role: string;
  emailVerified: boolean;
}

export interface NavbarSubscription {
  planSlug: string;
  planName: string;
  status: string;
  endDate: string | null;
  trialEndsAt: string | null;
}

export interface NavbarSavedEntry {
  id: string;
  templateId: string;
  templateName: string;
  templateCategory: string;
  templateIcon: string;
  scheduledFor: string;
  note: string;
}

interface NavbarInteractiveProps {
  user: NavbarUser | null;
  subscription: NavbarSubscription | null;
  favoriteTemplateIds: string[];
  savedEntries: NavbarSavedEntry[];
  supportEmail: string;
  phone: string;
}

export function NavbarInteractive({
  user,
  subscription,
  favoriteTemplateIds: initialFavoriteIds,
  savedEntries: initialSavedEntries,
  supportEmail,
  phone,
}: NavbarInteractiveProps) {
  const router = useRouter();
  const pathname = usePathname();
  const authenticated = !!user;
  const items = authenticated ? AUTHENTICATED_NAV.primary : PUBLIC_NAV.primary;

  const [favoriteIds, setFavoriteIds] =
    useState<string[]>(initialFavoriteIds);
  const [savedEntries, setSavedEntries] = useState(initialSavedEntries);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setFavoriteIds(initialFavoriteIds);
  }, [initialFavoriteIds]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setSavedEntries(initialSavedEntries);
  }, [initialSavedEntries]);

  const [openPanel, setOpenPanel] = useState<
    null | "search" | "favorites" | "calendar" | "profile"
  >(null);
  const closePanel = useCallback(() => setOpenPanel(null), []);

  useEffect(() => {
    if (!openPanel) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") closePanel();
    };
    const onClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement | null;
      if (!target) return;
      if (!target.closest("[data-navbar-panel]") && !target.closest("[data-navbar-trigger]")) {
        closePanel();
      }
    };
    document.addEventListener("keydown", onKey);
    document.addEventListener("mousedown", onClick);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("mousedown", onClick);
    };
  }, [openPanel, closePanel]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    closePanel();
  }, [pathname, closePanel]);

  const togglePanel = (panel: typeof openPanel) =>
    setOpenPanel((p) => (p === panel ? null : panel));

  const initials = useMemo(() => {
    if (!user) return "";
    return user.name
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((w) => w[0]?.toUpperCase() ?? "")
      .join("");
  }, [user]);

  const removeFavorite = useCallback(async (templateId: string) => {
    setFavoriteIds((ids) => ids.filter((id) => id !== templateId));
    try {
      await fetch(`/api/favorites/${templateId}`, { method: "DELETE" });
    } catch {
      router.refresh();
    }
  }, [router]);

  const removeSaved = useCallback(async (id: string) => {
    setSavedEntries((entries) => entries.filter((e) => e.id !== id));
    try {
      await fetch(`/api/calendar/saved-templates/${id}`, { method: "DELETE" });
    } catch {
      router.refresh();
    }
  }, [router]);

  return (
    <header className="navbar-shell relative">
      <div
        aria-hidden
        className="navbar-hero pointer-events-none absolute inset-0 -z-10"
      />

      <div className="navbar-topbar relative z-10 overflow-hidden">
        <FairyLights count={28} />
        <div className="relative z-10 mx-auto flex h-9 max-w-7xl items-center justify-between gap-4 px-4 text-xs text-rose-50/95 sm:px-6">
          <div className="hidden items-center gap-5 md:flex">
            <a
              href={`tel:${phone.replace(/\s+/g, "")}`}
              className="inline-flex items-center gap-1.5 hover:text-white"
            >
              <PhoneIcon className="h-3.5 w-3.5 text-amber-300" />
              <span>{phone}</span>
            </a>
            <a
              href={`mailto:${supportEmail}`}
              className="inline-flex items-center gap-1.5 hover:text-white"
            >
              <MailIcon className="h-3.5 w-3.5 text-amber-300" />
              <span>{supportEmail}</span>
            </a>
          </div>
          <div className="hidden flex-1 items-center justify-center text-[11px] tracking-wide md:flex">
            <span className="inline-flex items-center gap-1.5">
              <span aria-hidden>🎁</span>
              <span>Make Every Moment Special</span>
              <span aria-hidden className="text-rose-300">♥</span>
            </span>
          </div>
          <div className="ml-auto flex items-center gap-4">
            {!authenticated ? (
              <>
                <Link
                  href={PUBLIC_AUTH_ACTIONS.login.href}
                  className="hover:text-white"
                >
                  {PUBLIC_AUTH_ACTIONS.login.label}
                </Link>
                <Link
                  href={PUBLIC_AUTH_ACTIONS.register.href}
                  className="inline-flex items-center gap-1 rounded-full bg-white/95 px-3 py-1 text-[11px] font-semibold text-rose-700 shadow-sm hover:bg-white"
                >
                  Get a Quote
                  <ArrowIcon className="h-3 w-3" />
                </Link>
              </>
            ) : null}
          </div>
        </div>
      </div>

      <div className="navbar-mainbar relative">
        <div className="relative z-10 mx-auto flex h-16 max-w-7xl items-center justify-between gap-6 px-4 sm:px-6">
          <Link
            href={ROUTES.home}
            className="group flex items-center gap-2.5"
          >
            <LogoMark className="h-9 w-9" />
            <div className="flex flex-col leading-tight">
              <span className="text-lg font-bold tracking-tight text-foreground">
                {authenticated ? "EventFlow" : "Event Manager"}
              </span>
              <span className="text-[9px] font-medium uppercase tracking-[0.18em] text-rose-500">
                Plan · Celebrate · Cherish
              </span>
            </div>
          </Link>

          <nav aria-label="Primary" className="hidden md:block">
            <ul className="flex items-center gap-1">
              {items.map((item) => (
                <li key={item.href}>
                  <NavLink
                    href={item.href}
                    exact={item.exact}
                    className="rounded-full px-4 py-2 text-sm font-medium text-foreground/80 transition-colors hover:bg-rose-50 hover:text-rose-700"
                    activeClassName="bg-rose-100 text-rose-700"
                    inactiveClassName="text-foreground/80"
                  >
                    {item.label}
                  </NavLink>
                </li>
              ))}
            </ul>
          </nav>

          <div className="hidden items-center gap-2 md:flex">
            {authenticated ? (
              <>
                <button
                  type="button"
                  data-navbar-trigger
                  onClick={() => togglePanel("search")}
                  aria-label="Search templates"
                  aria-expanded={openPanel === "search"}
                  className="grid h-10 w-10 place-items-center rounded-full border border-rose-200 bg-white text-rose-500 transition-colors hover:bg-rose-50 hover:text-rose-700"
                >
                  <SearchIcon className="h-4 w-4" />
                </button>
                <button
                  type="button"
                  data-navbar-trigger
                  onClick={() => togglePanel("favorites")}
                  aria-label="Favorites"
                  aria-expanded={openPanel === "favorites"}
                  className="relative grid h-10 w-10 place-items-center rounded-full border border-rose-200 bg-white text-rose-500 transition-colors hover:bg-rose-50 hover:text-rose-700"
                >
                  <HeartIcon className="h-4 w-4" filled={favoriteIds.length > 0} />
                  {favoriteIds.length > 0 ? (
                    <span className="absolute -right-1 -top-1 grid h-4 w-4 place-items-center rounded-full bg-rose-500 text-[9px] font-semibold text-white">
                      {favoriteIds.length}
                    </span>
                  ) : null}
                </button>
                <button
                  type="button"
                  data-navbar-trigger
                  onClick={() => togglePanel("calendar")}
                  aria-label="Calendar"
                  aria-expanded={openPanel === "calendar"}
                  className="relative grid h-10 w-10 place-items-center rounded-full border border-rose-200 bg-white text-rose-500 transition-colors hover:bg-rose-50 hover:text-rose-700"
                >
                  <CalendarIcon className="h-4 w-4" />
                  {savedEntries.length > 0 ? (
                    <span className="absolute -right-1 -top-1 grid h-4 w-4 place-items-center rounded-full bg-amber-500 text-[9px] font-semibold text-white">
                      {savedEntries.length}
                    </span>
                  ) : null}
                </button>
                <button
                  type="button"
                  data-navbar-trigger
                  onClick={() => togglePanel("profile")}
                  aria-label="Open profile"
                  aria-expanded={openPanel === "profile"}
                  className="ml-1 inline-flex items-center gap-2 rounded-full border border-rose-200 bg-white py-1 pl-1 pr-3 text-foreground transition-colors hover:bg-rose-50"
                >
                  <span className="grid h-8 w-8 place-items-center rounded-full bg-gradient-to-br from-rose-500 to-pink-600 text-xs font-semibold text-white">
                    {initials || <ProfileIcon className="h-4 w-4" />}
                  </span>
                  <span className="hidden text-sm font-medium lg:inline">
                    {user?.name?.split(/\s+/)[0]}
                  </span>
                </button>
              </>
            ) : (
              <>
                <Link
                  href={PUBLIC_AUTH_ACTIONS.login.href}
                  className="inline-flex items-center justify-center rounded-lg border border-rose-200 bg-white px-4 py-2 text-sm font-medium text-foreground hover:bg-rose-50"
                >
                  {PUBLIC_AUTH_ACTIONS.login.label}
                </Link>
                <Link
                  href={PUBLIC_AUTH_ACTIONS.register.href}
                  className="inline-flex items-center gap-1.5 rounded-full bg-gradient-to-r from-rose-500 to-pink-600 px-5 py-2.5 text-sm font-semibold text-white shadow-md shadow-rose-500/30 transition-transform hover:scale-[1.03] hover:shadow-lg hover:shadow-rose-500/40"
                >
                  Plan My Event
                  <ArrowIcon className="h-3.5 w-3.5" />
                </Link>
              </>
            )}
          </div>

          <MobileMenu
            items={items}
            brandLabel="EventFlow"
            brandHref={ROUTES.home}
            brandLogo={<LogoMark className="h-7 w-7" />}
            secondaryAction={
              authenticated
                ? {
                    label: "Account",
                    href: AUTHENTICATED_AUTH_ACTIONS.account.href,
                  }
                : {
                    label: PUBLIC_AUTH_ACTIONS.login.label,
                    href: PUBLIC_AUTH_ACTIONS.login.href,
                  }
            }
            primaryAction={
              authenticated
                ? undefined
                : {
                    label: "Plan My Event",
                    href: PUBLIC_AUTH_ACTIONS.register.href,
                  }
            }
          />
        </div>
      </div>

      {openPanel === "search" ? (
        <div data-navbar-panel className="absolute inset-x-0 top-full z-40">
          <div className="mx-auto mt-2 max-w-2xl rounded-2xl border border-rose-100 bg-white/95 p-2 shadow-2xl shadow-rose-500/15 backdrop-blur">
            <SearchPopover
              authenticated={authenticated}
              favoriteIds={favoriteIds}
              onClose={closePanel}
            />
          </div>
        </div>
      ) : null}

      {openPanel === "favorites" && authenticated ? (
        <div data-navbar-panel className="absolute inset-x-0 top-full z-40">
          <div className="mx-auto mt-2 max-w-md rounded-2xl border border-rose-100 bg-white/95 shadow-2xl shadow-rose-500/15 backdrop-blur">
            <FavoritesPanel
              favoriteIds={favoriteIds}
              onRemove={removeFavorite}
              onClose={closePanel}
            />
          </div>
        </div>
      ) : null}

      {openPanel === "calendar" && authenticated ? (
        <div data-navbar-panel className="absolute inset-x-0 top-full z-40">
          <div className="mx-auto mt-2 max-w-lg rounded-2xl border border-rose-100 bg-white/95 shadow-2xl shadow-rose-500/15 backdrop-blur">
            <CalendarPanel
              entries={savedEntries}
              favoriteIds={favoriteIds}
              onAdd={(entry) => setSavedEntries((prev) => sortEntries([...prev, entry]))}
              onRemove={removeSaved}
              onClose={closePanel}
            />
          </div>
        </div>
      ) : null}

      {openPanel === "profile" && authenticated && user ? (
        <div data-navbar-panel className="absolute inset-x-0 top-full z-40">
          <div className="mx-auto mt-2 flex justify-end px-4 sm:px-6">
            <div className="w-full max-w-[280px]">
              <ProfilePanel user={user} subscription={subscription} onClose={closePanel} />
            </div>
          </div>
        </div>
      ) : null}
    </header>
  );
}

function sortEntries<T extends { scheduledFor: string }>(entries: T[]): T[] {
  return [...entries].sort((a, b) =>
    a.scheduledFor.localeCompare(b.scheduledFor),
  );
}

function HeartIcon({
  className,
  filled,
}: {
  className?: string;
  filled?: boolean;
}) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill={filled ? "currentColor" : "none"}
      stroke="currentColor"
      strokeWidth="2"
      className={className}
    >
      <path d="M12 21s-7.5-4.6-9.6-9.4C.7 7.5 3.5 4 7 4c2 0 3.6 1 5 2.6C13.4 5 15 4 17 4c3.5 0 6.3 3.5 4.6 7.6C19.5 16.4 12 21 12 21Z" />
    </svg>
  );
}
function SearchIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <circle cx="11" cy="11" r="7" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  );
}
function CalendarIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M16 3v4M8 3v4M3 11h18" />
    </svg>
  );
}
function ProfileIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <circle cx="12" cy="8" r="4" />
      <path d="M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6" />
    </svg>
  );
}
function ArrowIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  );
}
function PhoneIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" {...props}>
      <path d="M6.6 10.8a15.1 15.1 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25 11.4 11.4 0 0 0 3.6.57 1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1 11.4 11.4 0 0 0 .57 3.6 1 1 0 0 1-.25 1l-2.22 2.2Z" />
    </svg>
  );
}
function MailIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </svg>
  );
}
