'use client';

import { useEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
import { cn } from '@/lib/utils/cn';

export interface ContactAction {
  key: string;
  label: string;
  icon: ReactNode;
  onSelect: () => void;
  disabled?: boolean;
  /** Why it is disabled (tooltip). */
  title?: string;
  /** Drawn after a divider (e.g. Delete). */
  separated?: boolean;
  /** LD2: opens in a new tab: the external-link icon after the label (record.php `'ext'`). */
  external?: boolean;
}

/**
 * The "Actions" button of the contact card and its dropdown (design: details.php
 * `setupContactActionsMenu`, styles `.crm-contact-actions-menu` in details.css): a
 * search box and one row per action, anchored below the button on its right edge.
 *
 * On company detail, pass `hideTrigger` + `anchorRef` + `openRequest` so the More
 * quick-action opens the same menu without a separate Actions button.
 */
export function ContactActionsMenu({
  actions,
  disabled = false,
  openRequest = 0,
  triggerClassName = 'crm-contact-profile__actions',
  triggerLabel = 'Actions',
  hideTrigger = false,
  showSearch = true,
  anchorRef,
  keyboard = false,
}: {
  actions: ContactAction[];
  disabled?: boolean;
  /** Bump to open the menu from elsewhere (the "More" quick action). */
  openRequest?: number;
  /** Override trigger button class (e.g. company header `btn-crm`). */
  triggerClassName?: string;
  triggerLabel?: string;
  /** Hide the built-in Actions button (open via openRequest + anchorRef). */
  hideTrigger?: boolean;
  /** Search box at the top of the menu (contact detail keeps it; company More menu hides it). */
  showSearch?: boolean;
  /** Element used to position the menu when opened externally. */
  anchorRef?: RefObject<HTMLElement | null>;
  /**
   * R2 (contact and company record pages): the design's keys (record-actions.js:120-141).
   * Escape puts focus back on the button, arrows move between items, and Enter in the search
   * runs the first match. Off: Escape only closes, as before (Deals, the duplicates list).
   */
  keyboard?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [pos, setPos] = useState<{ top: number; left: number; width: number } | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const openRef = useRef(false);
  openRef.current = open;

  const place = () => {
    const el = anchorRef?.current ?? triggerRef.current;
    const rect = el?.getBoundingClientRect();
    if (!rect) return;
    const width = Math.min(255, window.innerWidth - 16);
    const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
    setPos({ top: Math.max(8, rect.bottom + 8), left, width });
  };

  // External trigger (e.g. company "More"): each bump toggles open/closed.
  useEffect(() => {
    if (openRequest === 0 || disabled) return;
    if (openRef.current) {
      setOpen(false);
      return;
    }
    place();
    setQuery('');
    setOpen(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- only react when request bumps
  }, [openRequest, disabled]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      const target = e.target as Node;
      if (menuRef.current?.contains(target)) return;
      if (triggerRef.current?.contains(target)) return;
      if (anchorRef?.current?.contains(target)) return;
      setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false);
        // R2 (`keyboard`): focus back on the button that opened it (record-actions.js:121-125).
        if (keyboard) (anchorRef?.current ?? triggerRef.current)?.focus();
        return;
      }
      if (!keyboard) return;
      const items = Array.from(
        menuRef.current?.querySelectorAll<HTMLButtonElement>(
          '.crm-contact-action-item:not(:disabled)',
        ) ?? [],
      );
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        // R2: arrow keys move between the items (record-actions.js:128-136).
        if (!items.length) return;
        e.preventDefault();
        const i = items.indexOf(document.activeElement as HTMLButtonElement);
        const next =
          e.key === 'ArrowDown' ? (i + 1) % items.length : i <= 0 ? items.length - 1 : i - 1;
        items[next]?.focus();
      } else if (
        e.key === 'Enter' &&
        document.activeElement instanceof HTMLInputElement &&
        menuRef.current?.contains(document.activeElement)
      ) {
        // R2: Enter in the search box runs the first match (record-actions.js:137-140).
        e.preventDefault();
        items[0]?.click();
      }
    };
    const onMove = (e: Event) => {
      if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    window.addEventListener('keydown', onKey);
    window.addEventListener('resize', onMove);
    window.addEventListener('scroll', onMove, true);
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', onMove);
      window.removeEventListener('scroll', onMove, true);
    };
  }, [open, anchorRef, keyboard]);

  const toggle = () => {
    if (open) {
      setOpen(false);
      return;
    }
    place();
    setQuery('');
    setOpen(true);
  };

  const q = query.trim().toLowerCase();
  const visible = actions.filter((a) => !q || a.label.toLowerCase().includes(q));

  return (
    <>
      {hideTrigger ? null : (
        <button
          ref={triggerRef}
          type="button"
          className={triggerClassName}
          aria-haspopup="menu"
          aria-expanded={open}
          disabled={disabled}
          onClick={toggle}
        >
          {triggerLabel}
          <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden>
            <path d="m7 10 5 5 5-5" fill="none" stroke="currentColor" strokeWidth="1.8" />
          </svg>
        </button>
      )}
      <div
        ref={menuRef}
        className={cn(
          'crm-contact-actions-menu',
          open && 'is-open',
          !showSearch && 'crm-contact-actions-menu--no-search',
        )}
        role="menu"
        aria-hidden={!open}
        style={pos ? { top: pos.top, left: pos.left, width: pos.width, right: 'auto' } : undefined}
      >
        {showSearch ? (
          <div className="crm-contact-actions-menu__search">
            <svg viewBox="0 0 24 24" aria-hidden>
              <circle cx="11" cy="11" r="6.5" />
              <path d="m16 16 4 4" />
            </svg>
            <input
              type="search"
              placeholder="Search"
              autoComplete="off"
              aria-label="Search actions"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
          </div>
        ) : null}
        <div className="crm-contact-actions-menu__items">
          {visible.map((a) => (
            <div key={a.key}>
              {a.separated ? <div className="crm-contact-actions-menu__divider" /> : null}
              <button
                type="button"
                className="crm-contact-action-item"
                role="menuitem"
                disabled={a.disabled}
                title={a.title}
                onClick={() => {
                  setOpen(false);
                  a.onSelect();
                }}
              >
                <span className="crm-contact-action-item__icon">{a.icon}</span>
                <span className="crm-contact-action-item__label">{a.label}</span>
                {a.external ? (
                  <svg
                    className="crm-contact-action-item__ext"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    width="14"
                    height="14"
                    aria-label="Opens in a new tab"
                    role="img"
                  >
                    <path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" />
                  </svg>
                ) : null}
              </button>
            </div>
          ))}
          {visible.length === 0 ? (
            <p className="crm-fs-8 crm-text-muted" style={{ padding: '6px 16px' }}>
              No matching action
            </p>
          ) : null}
        </div>
      </div>
    </>
  );
}
