'use client';

/**
 * The Comment tab's box (inbox-hs.js mentionCheck / pickMention): typing "@" and a name lists
 * matching teammates (`.ix-mention`); picking one writes "@Name " and remembers who it was, so
 * the comment notifies them.
 */
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { insertMention, mentionHits, mentionQuery, type Mentionable } from '../conversation';
import { ixInitials } from './ix';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

export const MentionTextarea = forwardRef<
  HTMLTextAreaElement,
  {
    id: string;
    value: string;
    people: Mentionable[];
    disabled: boolean;
    placeholder: string;
    onChange: (text: string) => void;
    onMention: (person: Mentionable) => void;
  }
>(function MentionTextarea({ id, value, people, disabled, placeholder, onChange, onMention }, ref) {
  const box = useRef<HTMLTextAreaElement>(null);
  useImperativeHandle(ref, () => box.current as HTMLTextAreaElement);
  const [state, setState] = useState<{
    start: number;
    caret: number;
    hits: Mentionable[];
    active: number;
    left: number;
    top: number;
  } | null>(null);

  const check = (text: string, caret: number) => {
    const q = mentionQuery(text, caret);
    const hits = q ? mentionHits(people, q.query) : [];
    if (!q || !hits.length || !box.current) {
      setState(null);
      return;
    }
    const r = box.current.getBoundingClientRect();
    setState({ start: q.start, caret, hits, active: 0, left: r.left, top: r.top });
  };

  const pick = (person: Mentionable) => {
    if (!state) return;
    const next = insertMention(value, state.start, state.caret, person.name);
    onChange(next.text);
    onMention(person);
    setState(null);
    requestAnimationFrame(() => {
      box.current?.focus();
      box.current?.setSelectionRange(next.caret, next.caret);
    });
  };

  return (
    <>
      <SnippetTextarea
        id={id}
        ref={box}
        rows={3}
        value={value}
        disabled={disabled}
        placeholder={placeholder}
        aria-autocomplete="list"
        aria-controls={state ? `${id}-mentions` : undefined}
        onChange={(e) => {
          onChange(e.target.value);
          check(e.target.value, e.target.selectionStart);
        }}
        onClick={(e) => check(value, e.currentTarget.selectionStart)}
        onBlur={() => window.setTimeout(() => setState(null), 150)}
        onKeyDown={(e) => {
          if (!state) return;
          if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
            e.preventDefault();
            const n = state.hits.length;
            const step = e.key === 'ArrowDown' ? 1 : -1;
            setState({ ...state, active: (state.active + step + n) % n });
          } else if (e.key === 'Enter' || e.key === 'Tab') {
            e.preventDefault();
            const person = state.hits[state.active];
            if (person) pick(person);
          } else if (e.key === 'Escape') {
            e.preventDefault();
            setState(null);
          }
        }}
      />
      {state ? (
        <div
          id={`${id}-mentions`}
          className="ix-mention"
          role="listbox"
          aria-label="Mention a teammate"
          style={{
            left: Math.max(8, state.left),
            top: state.top - 6,
            transform: 'translateY(-100%)',
          }}
        >
          {state.hits.map((p, i) => (
            <button
              key={p.id}
              type="button"
              role="option"
              aria-selected={i === state.active}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => pick(p)}
            >
              <span className="ix-av ix-av--sm">{ixInitials(p.name)}</span>
              {p.name}
            </button>
          ))}
        </div>
      ) : null}
    </>
  );
});
