"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useToastStore } from "@/lib/stores/toast-store";

// R14 B.1: kebab menu for in-chat moderation actions. Earlier the only path
// to Report or Block someone was to leave the conversation, navigate to the
// other user's profile, scroll to ProfileActions, and click there. For
// safety-critical features (a user receiving harassment) this friction was
// genuine harm. Keeps both actions one tap away.
export default function ChatHeaderMenu({
  otherUserId,
  otherUsername,
}: {
  otherUserId: number;
  otherUsername: string;
}) {
  const [open, setOpen] = useState(false);
  const [blocking, setBlocking] = useState(false);
  const [blocked, setBlocked] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const addToast = useToastStore((s) => s.addToast);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  async function handleBlock() {
    if (blocked || blocking) return;
    setBlocking(true);
    try {
      const res = await fetch("/api/blocks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ blocked_user_id: otherUserId }),
      });
      if (res.ok || res.status === 409) {
        setBlocked(true);
        addToast("success", `${otherUsername} has been blocked.`);
      } else {
        addToast("error", "Couldn't block — please try again.");
      }
    } catch {
      addToast("error", "Network error while blocking.");
    } finally {
      setBlocking(false);
      setOpen(false);
    }
  }

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="p-2 rounded-lg hover:bg-surface-light transition-colors text-text-muted hover:text-text"
        aria-label="Conversation actions"
        aria-haspopup="menu"
        aria-expanded={open}
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01" />
        </svg>
      </button>

      {open && (
        <div
          role="menu"
          className="absolute right-0 top-full mt-2 z-30 w-52 bg-surface border border-surface-light rounded-lg shadow-elevated overflow-hidden"
        >
          <Link
            href={`/support/new/report-member?user=${otherUserId}`}
            role="menuitem"
            className="block px-4 py-2.5 text-sm text-text hover:bg-surface-light transition-colors"
            onClick={() => setOpen(false)}
          >
            Report this user
          </Link>
          <button
            type="button"
            role="menuitem"
            onClick={handleBlock}
            disabled={blocking || blocked}
            className="block w-full text-left px-4 py-2.5 text-sm text-red-400 hover:bg-surface-light transition-colors disabled:opacity-50"
          >
            {blocked ? "Blocked" : blocking ? "Blocking…" : "Block"}
          </button>
        </div>
      )}
    </div>
  );
}
