'use client';

/**
 * HUB-417: snippets in a plain text box (call notes, meeting notes, editing a logged activity,
 * internal comments): "#shortcut" while typing, and "Insert snippet" under the box for the same
 * list as the rich composers. The snippet goes in as plain text.
 */
import {
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
  type TextareaHTMLAttributes,
} from 'react';
import type { SnippetTarget } from '../api.client';
import { snippetPlainText } from '../model';
import { SnippetMenu } from './SnippetMenu';
import { useSnippetHash } from './useSnippetHash';

export const SnippetTextarea = forwardRef<
  HTMLTextAreaElement,
  TextareaHTMLAttributes<HTMLTextAreaElement> & {
    snippetTarget?: SnippetTarget;
    /** For a box that closes when it loses focus: "#shortcut" only. */
    typingOnly?: boolean;
  }
>(function SnippetTextarea(
  { snippetTarget = {}, typingOnly = false, onKeyDown, onInput, onBlur, ...props },
  forwarded,
) {
  const ref = useRef<HTMLTextAreaElement>(null);
  useImperativeHandle(forwarded, () => ref.current!, []);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const off = Boolean(props.disabled || props.readOnly);

  /** Replaces `start`–`end` with `text`, as if typed, so the form's own state follows. */
  const put = (start: number, end: number, text: string) => {
    const box = ref.current;
    if (!box) return;
    box.focus();
    box.setSelectionRange(start, end);
    if (typeof document.execCommand === 'function') {
      if (document.execCommand('insertText', false, text)) return;
    }
    const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;
    setValue?.call(box, box.value.slice(0, start) + text + box.value.slice(end));
    box.dispatchEvent(new Event('input', { bubbles: true }));
  };

  const hash = useSnippetHash<number>({
    target: snippetTarget,
    off,
    caret: () => {
      const box = ref.current;
      return box
        ? { before: box.value.slice(0, box.selectionStart), at: box.selectionStart }
        : null;
    },
    replace: (end, typed, html) => {
      const start = end - typed.length - 1;
      // Typed over meanwhile: leave it.
      if (start < 0 || ref.current?.value.slice(start, end).toLowerCase() !== `#${typed}`) return;
      put(start, end, snippetPlainText(html));
    },
  });

  return (
    <div className="sn-textarea">
      <textarea
        {...props}
        ref={ref}
        onInput={(e) => {
          onInput?.(e);
          hash.track();
        }}
        onKeyDown={(e) => {
          if (hash.onKeyDown(e)) {
            e.preventDefault();
            e.stopPropagation(); // Esc closes the list, not the dialog around the box
            return;
          }
          onKeyDown?.(e);
        }}
        onBlur={(e) => {
          hash.close();
          onBlur?.(e);
        }}
      />
      {hash.list}
      {off || typingOnly ? null : (
        <>
          <button
            ref={buttonRef}
            type="button"
            className="sn-textarea__insert"
            aria-haspopup="dialog"
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen((o) => !o)}
          >
            Insert snippet
          </button>
          <SnippetMenu
            open={menuOpen}
            anchorRef={buttonRef}
            onClose={() => setMenuOpen(false)}
            target={snippetTarget}
            onInsert={(html) => {
              const box = ref.current;
              if (box) put(box.selectionStart, box.selectionEnd, snippetPlainText(html));
            }}
          />
        </>
      )}
    </div>
  );
});
