"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { NavLink } from "@/components/navigation/NavLink";
import { ROUTES } from "@/config/routes.config";
import type { NavItem } from "@/config/navigation.config";

export type MobileMenuAuthAction =
  | { label: string; href: string; variant?: "primary" | "secondary" }
  | { label: string; kind: "logout"; variant?: "primary" | "secondary" };

export interface MobileMenuProps {
  items: NavItem[];
  primaryAction?: MobileMenuAuthAction;
  secondaryAction?: MobileMenuAuthAction;
  brandLabel: string;
  brandHref: string;
  brandLogo?: ReactNode;
}

export function MobileMenu({
  items,
  primaryAction,
  secondaryAction,
  brandLabel,
  brandHref,
  brandLogo,
}: MobileMenuProps) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();

  useEffect(() => {
    // Close the menu when the route changes (e.g. via browser back/forward).
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setOpen(false);
  }, [pathname]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  const close = () => setOpen(false);

  return (
    <div className="sm:hidden">
      <button
        type="button"
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        aria-controls="mobile-menu"
        onClick={() => setOpen((v) => !v)}
        className="inline-flex items-center justify-center rounded-md p-2 text-foreground hover:bg-surface-muted transition-colors"
      >
        {open ? (
          <svg
            className="h-6 w-6"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            aria-hidden="true"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="M6 6l12 12M18 6L6 18" />
          </svg>
        ) : (
          <svg
            className="h-6 w-6"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            aria-hidden="true"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="M4 7h16M4 12h16M4 17h16" />
          </svg>
        )}
      </button>

      {open ? (
        <div
          id="mobile-menu"
          className="absolute inset-x-0 top-full z-40 border-b border-border bg-surface shadow-md"
        >
          <nav
            aria-label="Mobile primary"
            className="mx-auto flex max-w-6xl flex-col gap-1 px-4 py-3"
          >
            <Link
              href={brandHref}
              className="flex items-center gap-2 px-2 py-2 text-base font-semibold text-foreground"
              onClick={close}
            >
              {brandLogo}
              <span>{brandLabel}</span>
            </Link>
            <ul className="flex flex-col gap-1">
              {items.map((item) => (
                <li key={item.href}>
                  <NavLink
                    href={item.href}
                    exact={item.exact}
                    className="block w-full rounded-md px-2 py-2 text-base hover:bg-surface-muted"
                    activeClassName="text-primary bg-surface-muted"
                  >
                    {item.label}
                  </NavLink>
                </li>
              ))}
            </ul>

            <div className="mt-3 flex flex-col gap-2 border-t border-border pt-3">
              {secondaryAction ? (
                "kind" in secondaryAction ? (
                  <LogoutAction label={secondaryAction.label} onDone={close} secondary />
                ) : (
                  <Link
                    href={secondaryAction.href}
                    onClick={close}
                    className="inline-flex items-center justify-center rounded-lg border border-border bg-surface px-4 py-2 text-sm font-medium text-foreground hover:bg-surface-muted transition-colors"
                  >
                    {secondaryAction.label}
                  </Link>
                )
              ) : null}

              {primaryAction ? (
                "kind" in primaryAction ? (
                  <LogoutAction label={primaryAction.label} onDone={close} />
                ) : (
                  <Link
                    href={primaryAction.href}
                    onClick={close}
                    className="inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary-hover transition-colors"
                  >
                    {primaryAction.label}
                  </Link>
                )
              ) : null}
            </div>
          </nav>
        </div>
      ) : null}
    </div>
  );
}

function LogoutAction({
  label,
  onDone,
  secondary,
}: {
  label: string;
  onDone: () => void;
  secondary?: boolean;
}) {
  const [loading, setLoading] = useState(false);
  const className = secondary
    ? "inline-flex items-center justify-center rounded-lg border border-border bg-surface px-4 py-2 text-sm font-medium text-foreground hover:bg-surface-muted transition-colors"
    : "inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary-hover transition-colors";

  async function handle() {
    setLoading(true);
    try {
      await fetch("/api/auth/logout", { method: "POST" });
    } catch {
      // ignore — still navigate away
    }
    onDone();
    window.location.href = ROUTES.login;
  }

  return (
    <button
      type="button"
      onClick={handle}
      disabled={loading}
      className={className}
    >
      {loading ? "Signing out…" : label}
    </button>
  );
}