"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { MdMoreVert } from "react-icons/md";
import { useModal } from "../../../../../lib/modal-system/ModalContext";
import { AdminContactRequest } from "../../../../../hooks/features/admin/contact/useContactRequestsFetch";

interface ContactActionsMenuProps {
  contact: AdminContactRequest;
}

type MenuPosition = {
  top: number;
  left: number;
  origin: "top" | "bottom";
};

const MENU_WIDTH = 160;
const MENU_HEIGHT = 88;
const GAP = 8;
const SCREEN_PADDING = 12;

export function ContactActionsMenu({ contact }: ContactActionsMenuProps) {
  const [open, setOpen] = useState(false);
  const [position, setPosition] = useState<MenuPosition>({
    top: 0,
    left: 0,
    origin: "top",
  });
  const buttonRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const { openModal } = useModal();

  const updatePosition = useCallback(() => {
    const button = buttonRef.current;
    if (!button) return;

    const rect = button.getBoundingClientRect();
    const spaceBottom = window.innerHeight - rect.bottom;
    const spaceTop = rect.top;
    const openUp = spaceBottom < MENU_HEIGHT + GAP && spaceTop > spaceBottom;

    const top = openUp
      ? Math.max(SCREEN_PADDING, rect.top - MENU_HEIGHT - GAP)
      : Math.min(
          rect.bottom + GAP,
          window.innerHeight - MENU_HEIGHT - SCREEN_PADDING,
        );

    let left = rect.right - MENU_WIDTH;
    left = Math.max(SCREEN_PADDING, left);
    left = Math.min(left, window.innerWidth - MENU_WIDTH - SCREEN_PADDING);

    setPosition({
      top,
      left,
      origin: openUp ? "bottom" : "top",
    });
  }, []);

  const handleOpen = () => {
    updatePosition();
    setOpen((prev) => !prev);
  };

  useEffect(() => {
    if (!open) return;

    const handleOutsideClick = (event: MouseEvent) => {
      const target = event.target as Node;

      if (
        buttonRef.current?.contains(target) ||
        menuRef.current?.contains(target)
      ) {
        return;
      }

      setOpen(false);
    };

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };

    window.addEventListener("resize", updatePosition);
    window.addEventListener("scroll", updatePosition, true);
    document.addEventListener("mousedown", handleOutsideClick);
    document.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("resize", updatePosition);
      window.removeEventListener("scroll", updatePosition, true);
      document.removeEventListener("mousedown", handleOutsideClick);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [open, updatePosition]);

  return (
    <>
      <button
        ref={buttonRef}
        type="button"
        onClick={(event) => {
          event.stopPropagation();
          handleOpen();
        }}
        aria-label={`Actions for ${contact.name}`}
        className="inline-flex h-8 w-8 items-center justify-center rounded-full text-link-1 transition hover:bg-link-1/10 focus:outline-none focus:ring-2 focus:ring-link-1/30"
      >
        <MdMoreVert size={20} />
      </button>

      {open && typeof document !== "undefined" &&
        createPortal(
          <div
            ref={menuRef}
            role="menu"
            style={{
              top: position.top,
              left: position.left,
              width: MENU_WIDTH,
              transformOrigin:
                position.origin === "top" ? "top right" : "bottom right",
            }}
            className="fixed z-60 overflow-hidden rounded-xl border border-black/5 bg-white py-1.5 shadow-[0_12px_40px_rgba(15,23,42,0.18)] ring-1 ring-black/5"
          >
            <button
              type="button"
              role="menuitem"
              onClick={(event) => {
                event.stopPropagation();
                setOpen(false);
                openModal("CONTACT_REQUEST_INFO", { uuid: contact.uuid });
              }}
              className="block w-full px-4 py-2.5 text-left text-sm font-medium text-slate-700 transition hover:bg-link-1/5"
            >
              View
            </button>
          </div>,
          document.body,
        )}
    </>
  );
}
