'use client';

/**
 * HUB-417: "#shortcut" for a writing box that is not one of the rich composers (a plain text box,
 * the task page's notes). Typing `#` and a few letters lists the matching snippets (arrows move,
 * Enter or Tab puts one in, Esc closes); a whole shortcut followed by Space or Enter works too.
 */
import { useCallback, useRef, useState, type KeyboardEvent, type RefObject } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  applySnippet,
  getSnippetByShortcut,
  listSnippets,
  type Snippet,
  type SnippetTarget,
} from '../api.client';
import {
  hashQueryBeforeCaret,
  keepInView,
  matchSnippets,
  readySnippet,
  shortcutBeforeCaret,
} from '../model';
import { SnippetLoadError } from './SnippetLoadError';

/**
 * The list a "#shortcut" box searches, loaded at its first "#" and kept. A failed load is not an
 * empty list (go-live QA: it read "No snippets match"); it is tried again at the next "#" or from
 * the list's "Try again".
 */
export function useSnippetList() {
  const [snippets, setSnippets] = useState<Snippet[] | null>(null);
  const [failed, setFailed] = useState(false);
  const asked = useRef(false);
  const load = useCallback(() => {
    if (asked.current) return;
    asked.current = true;
    setFailed(false);
    listSnippets().then(
      (res) => setSnippets(res.data),
      () => {
        asked.current = false;
        setFailed(true);
      },
    );
  }, []);
  return { snippets, failed, load };
}

export interface SnippetCaret<At> {
  /** The text before the caret. */
  before: string;
  /** Where the caret is, for `replace`. */
  at: At;
}

export function useSnippetHash<At>({
  target,
  off = false,
  caret,
  replace,
}: {
  target: SnippetTarget;
  off?: boolean;
  /** Null when the caret is not in the box. */
  caret: () => SnippetCaret<At> | null;
  /** Replaces `#typed` ending at `at` with the filled snippet, unless it was typed over. */
  replace: (at: At, typed: string, html: string) => void;
}) {
  const toast = useToast();
  const [query, setQuery] = useState<string | null>(null);
  const [index, setIndex] = useState(0);
  const { snippets, failed, load } = useSnippetList();
  const matches = query !== null && snippets ? matchSnippets(snippets, query) : [];

  const expand = async (snippet: Snippet | null, typed: string, at: At) => {
    setQuery(null);
    let filled: { bodyHtml: string; missingFields: string[] };
    try {
      const found = snippet ?? (await getSnippetByShortcut(typed));
      filled = await applySnippet(found.id, target);
    } catch (err) {
      // No snippet has that shortcut: the text stays as typed.
      if (!(isApiError(err) && err.isNotFound)) toast(errorText(err), 'danger');
      return;
    }
    const ready = readySnippet(filled);
    replace(at, typed, ready.html);
    if (ready.notice) toast(ready.notice, 'danger', { durationMs: 8000 });
  };

  /** Call after typing: opens, updates or closes the list. */
  const track = () => {
    if (off) return;
    const here = caret();
    const next = here ? hashQueryBeforeCaret(here.before) : null;
    if (next !== null) load();
    if (next !== query) setIndex(0);
    setQuery(next);
  };

  const pick = (snippet: Snippet) => {
    const here = caret();
    const typed = here ? hashQueryBeforeCaret(here.before) : null;
    if (here && typed !== null) void expand(snippet, typed, here.at);
  };

  /** True when the key was for the snippet list: the box should do nothing else with it. */
  const onKeyDown = (e: KeyboardEvent): boolean => {
    if (off) return false;
    if (query !== null && matches.length) {
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        const step = e.key === 'ArrowDown' ? 1 : matches.length - 1;
        setIndex((i) => (i + step) % matches.length);
        return true;
      }
      if (e.key === 'Enter' || e.key === 'Tab') {
        pick(matches[Math.min(index, matches.length - 1)]!);
        return true;
      }
    }
    if (query !== null && e.key === 'Escape') {
      setQuery(null);
      return true;
    }
    if (e.key === ' ' || e.key === 'Enter') {
      const here = caret();
      const typed = here ? shortcutBeforeCaret(here.before) : null;
      setQuery(null);
      // The key still types; the shortcut before it is then replaced.
      if (here && typed) void expand(null, typed, here.at);
    }
    return false;
  };

  const list =
    query !== null && (failed || (snippets && (matches.length || query))) ? (
      <div className="sn-textarea__list" role="listbox" aria-label="Snippets">
        {failed ? (
          <SnippetLoadError className="sn-textarea__none" onRetry={load} />
        ) : matches.length ? (
          matches.map((s, i) => (
            <button
              key={s.id}
              ref={i === index ? keepInView : undefined}
              type="button"
              role="option"
              aria-selected={i === index}
              className={cn('sn-textarea__item', i === index && 'is-selected')}
              onMouseDown={(e) => e.preventDefault()}
              onMouseEnter={() => setIndex(i)}
              onClick={() => pick(s)}
            >
              {s.name} <small>#{s.shortcut}</small>
            </button>
          ))
        ) : (
          <div className="sn-textarea__none">No snippets match #{query}</div>
        )}
      </div>
    ) : null;

  return { track, onKeyDown, list, close: () => setQuery(null) };
}

/** `useSnippetHash` for a contentEditable box: where its caret is, and putting a snippet there. */
export function useEditableSnippetHash(
  box: RefObject<HTMLElement | null>,
  { target, off }: { target: SnippetTarget; off?: boolean },
) {
  return useSnippetHash<{ node: Text; offset: number }>({
    target,
    off,
    caret: () => {
      const selection = window.getSelection();
      const node = selection?.anchorNode;
      if (!selection?.isCollapsed || !node || node.nodeType !== Node.TEXT_NODE) return null;
      if (!box.current?.contains(node)) return null;
      const offset = selection.anchorOffset;
      return {
        before: (node as Text).data.slice(0, offset),
        at: { node: node as Text, offset },
      };
    },
    replace: ({ node, offset }, typed, html) => {
      const start = offset - typed.length - 1;
      // Typed over or moved meanwhile: leave it.
      if (!box.current?.contains(node) || start < 0) return;
      if (node.data.slice(start, offset).toLowerCase() !== `#${typed}`) return;
      const range = document.createRange();
      range.setStart(node, start);
      range.setEnd(node, offset);
      box.current.focus();
      const selection = window.getSelection();
      selection?.removeAllRanges();
      selection?.addRange(range);
      document.execCommand('insertHTML', false, html);
    },
  });
}
