"use client";

import React from "react";
import Link from "next/link";
import { useMessageModal } from "@/app/components/ui/MessageModalProvider";

type Props = {
  userId?: string | null;
  nickname?: string | null;
  isAnonymous?: boolean;
  className?: string;
  underlineOnHover?: boolean;
};

export function UserNameMenu({
  userId,
  nickname,
  isAnonymous,
  className,
  underlineOnHover = true,
}: Props) {
  const { openMessageModal } = useMessageModal();
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (!ref.current) return;
      if (!ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    function onEsc(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("mousedown", onClickOutside);
    document.addEventListener("keydown", onEsc);
    return () => {
      document.removeEventListener("mousedown", onClickOutside);
      document.removeEventListener("keydown", onEsc);
    };
  }, []);

  const label = isAnonymous ? "익명" : (nickname ?? "익명");
  const canInteract = !!userId && !isAnonymous;

  if (!canInteract) {
    return (
      <span className={className}>{label}</span>
    );
  }

  return (
    <div ref={ref} className={`relative inline-block ${className || ""}`}>
      <button
        type="button"
        className={`text-left ${underlineOnHover ? "hover:underline" : ""} text-inherit cursor-pointer`}
        onClick={() => setOpen((v) => !v)}
        aria-haspopup="menu"
        aria-expanded={open}
      >
        {label}
      </button>
      {open && (
        <div
          role="menu"
          className="absolute z-50 mt-1 w-36 rounded-md border border-neutral-200 bg-white shadow-md overflow-hidden"
        >
          <Link
            href={`/users/${encodeURIComponent(userId!)}`}
            className="block px-3 py-2 text-sm text-neutral-800 hover:bg-neutral-50"
            role="menuitem"
            onClick={() => setOpen(false)}
          >
            프로필 보기
          </Link>
          <button
            type="button"
            className="w-full text-left block px-3 py-2 text-sm text-neutral-800 hover:bg-neutral-50 cursor-pointer"
            role="menuitem"
            onClick={() => {
              openMessageModal({ receiverId: userId!, receiverNickname: nickname ?? null });
              setOpen(false);
            }}
          >
            쪽지쓰기
          </button>
        </div>
      )}
    </div>
  );
}


