"use client";

import { useEffect, useRef } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { X, ArrowUpRight, Mail, Phone } from "lucide-react";
import { Logo } from "@/components/common/Logo";
import { ButtonLink } from "@/components/common/Button";
import { LanguageDropdown } from "@/components/i18n/LanguageDropdown";
import { NAV_LINKS, SITE } from "@/constants/site";
import { useTranslation } from "@/hooks/useTranslation";
import { useAuth } from "@/hooks/useAuth";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { cn } from "@/lib/utils";

interface MobileMenuProps {
  open: boolean;
  onClose: () => void;
}

export function MobileMenu({ open, onClose }: MobileMenuProps) {
  const { t, dir } = useTranslation();
  const { user, hydrated } = useAuth();
  const { user: agentUser, hydrated: agentHydrated } = useAgentAuth();
  const pathname = usePathname();
  const showLoggedIn = hydrated && !!user;
  const showAgentLoggedIn = agentHydrated && !!agentUser;
  const panelRef = useRef<HTMLDivElement>(null);
  const previousActive = useRef<HTMLElement | null>(null);

  // Lock body scroll while open
  useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      previousActive.current = document.activeElement as HTMLElement | null;
      // Move focus into the panel
      requestAnimationFrame(() => {
        const firstFocusable = panelRef.current?.querySelector<HTMLElement>(
          "button, a, input, [tabindex]:not([tabindex='-1'])",
        );
        firstFocusable?.focus();
      });
    } else {
      document.body.style.overflow = "";
      // Restore focus when closing
      previousActive.current?.focus();
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  // Escape to close
  useEffect(() => {
    if (!open) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // RTL-aware slide direction
  const slideClosed = dir === "rtl" ? "-translate-x-full" : "translate-x-full";

  return (
    <div
      className={cn(
        "fixed inset-0 z-50 lg:hidden",
        open ? "pointer-events-auto" : "pointer-events-none",
      )}
      aria-hidden={!open}
    >
      {/* Backdrop */}
      <div
        className={cn(
          "absolute inset-0 bg-slate-900/60 backdrop-blur-md transition-opacity duration-300 ease-snappy",
          open ? "opacity-100" : "opacity-0",
        )}
        onClick={onClose}
      />

      {/* Slide-in panel */}
      <div
        ref={panelRef}
        className={cn(
          "absolute inset-y-0 end-0 flex w-[88%] max-w-sm flex-col overflow-y-auto bg-white shadow-elevated transition-transform duration-400 ease-snappy dark:bg-slate-950",
          open ? "translate-x-0" : slideClosed,
        )}
        role="dialog"
        aria-modal="true"
        aria-label="Navigation menu"
      >
        {/* Header */}
        <div className="sticky top-0 z-10 flex h-16 items-center justify-between border-b border-slate-200/70 bg-white/95 px-5 backdrop-blur-xl dark:border-slate-800/70 dark:bg-slate-950/95">
          <Logo />
          <button
            type="button"
            aria-label="Close menu"
            onClick={onClose}
            className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-700 transition-all duration-200 ease-snappy hover:rotate-90 hover:border-slate-300 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:border-slate-600 dark:hover:bg-slate-800"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Nav */}
        <nav className="flex flex-1 flex-col px-3 py-4" aria-label="Mobile primary">
          {NAV_LINKS.map((link, idx) => {
            const active =
              link.href === "/"
                ? pathname === "/"
                : pathname.startsWith(link.href);
            return (
              <Link
                key={link.href}
                href={link.href}
                aria-current={active ? "page" : undefined}
                style={{
                  transitionDelay: open ? `${60 + idx * 35}ms` : "0ms",
                }}
                className={cn(
                  "group flex items-center justify-between rounded-2xl px-4 py-3.5 text-base font-medium transition-all duration-300 ease-snappy",
                  open ? "opacity-100 translate-x-0" : "opacity-0 translate-x-4",
                  active
                    ? "bg-brand-50 text-brand-700 shadow-soft dark:bg-brand-500/15 dark:text-brand-300"
                    : "text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-200 dark:hover:bg-slate-800/70 dark:hover:text-white",
                )}
              >
                <span>{t(link.key)}</span>
                <ArrowUpRight
                  className={cn(
                    "h-4 w-4 opacity-0 transition-all duration-200 group-hover:opacity-60",
                    dir === "rtl" && "rotate-[-90deg]",
                  )}
                />
              </Link>
            );
          })}
        </nav>

        {/* Footer actions */}
        <div className="border-t border-slate-200/70 bg-slate-50/50 px-5 py-5 dark:border-slate-800/70 dark:bg-slate-900/40">
          {showLoggedIn ? (
            <ButtonLink
              href="/dashboard"
              variant="primary"
              size="lg"
              className="w-full"
            >
              {t("app.nav.goToDashboard")}
            </ButtonLink>
          ) : showAgentLoggedIn ? (
            <ButtonLink
              href="/agent/dashboard"
              variant="primary"
              size="lg"
              className="w-full"
            >
              {t("app.nav.goToDashboard")}
            </ButtonLink>
          ) : (
            <div className="flex flex-col gap-3">
              <ButtonLink
                href="/register"
                variant="primary"
                size="lg"
                className="w-full"
              >
                {t("nav.getStarted")}
              </ButtonLink>
              <ButtonLink
                href="/login"
                variant="outline"
                size="lg"
                className="w-full"
              >
                {t("nav.signIn")}
              </ButtonLink>
            </div>
          )}

          <div className="mt-5 flex items-center justify-between gap-3">
            <LanguageDropdown />
          </div>

          <div className="mt-5 space-y-2 border-t border-slate-200/70 pt-5 dark:border-slate-800/70">
            <a
              href={`mailto:${SITE.email}`}
              className="flex items-center gap-3 text-sm text-slate-600 hover:text-brand-700 dark:text-slate-300 dark:hover:text-brand-300"
            >
              <Mail className="h-4 w-4" />
              <span>{SITE.email}</span>
            </a>
            <a
              href={`tel:${SITE.phone.replace(/[^\d+]/g, "")}`}
              className="flex items-center gap-3 text-sm text-slate-600 hover:text-brand-700 dark:text-slate-300 dark:hover:text-brand-300"
            >
              <Phone className="h-4 w-4" />
              <span dir="ltr">{SITE.phone}</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}
