'use client';

import { useEffect, useMemo, useState, type RefObject } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { applySnippet, listSnippets, type Snippet, type SnippetTarget } from '../api.client';
import { readySnippet, snippetPlainText } from '../model';
import { SnippetLoadError } from './SnippetLoadError';

/** The composer's Insert snippet list (also under plain text boxes). Loads when opened; a failed load says so in the list. */
export function SnippetMenu({
  open,
  anchorRef,
  onClose,
  target,
  onInsert,
}: {
  open: boolean;
  anchorRef: RefObject<HTMLElement | null>;
  onClose: () => void;
  target: SnippetTarget;
  onInsert: (html: string) => void;
}) {
  const toast = useToast();
  const [snippets, setSnippets] = useState<Snippet[] | null>(null);
  const [failed, setFailed] = useState(false);
  const [query, setQuery] = useState('');
  /** The entry under the pointer or the keyboard, previewed below the list. */
  const [hovered, setHovered] = useState<string | null>(null);
  /** "Try again" after a list that could not load. */
  const [attempt, setAttempt] = useState(0);

  useEffect(() => {
    if (!open) return;
    setQuery('');
    setHovered(null);
    setFailed(false);
    let alive = true;
    listSnippets().then(
      (res) => {
        if (alive) setSnippets(res.data);
      },
      () => {
        if (alive) setFailed(true);
      },
    );
    return () => {
      alive = false;
    };
  }, [open, attempt]);

  const shown = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!snippets) return [];
    return q
      ? snippets.filter((s) => `${s.name} ${s.shortcut}`.toLowerCase().includes(q))
      : snippets;
  }, [snippets, query]);

  const previewed = shown.find((s) => s.id === hovered) ?? shown[0];

  const pick = async (snippet: Snippet) => {
    onClose();
    try {
      const filled = await applySnippet(snippet.id, target);
      const ready = readySnippet(filled);
      onInsert(ready.html);
      if (ready.notice) toast(ready.notice, 'danger', { durationMs: 8000 });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  return (
    <AnchoredPopover
      open={open}
      anchorRef={anchorRef}
      onClose={onClose}
      className="acx-pop--list"
      label="Insert snippet"
      width={340}
      maxHeight={460}
      preferred="up"
    >
      <label className="acx-search">
        <input
          type="search"
          placeholder="Search snippets"
          autoComplete="off"
          autoFocus
          aria-label="Search snippets"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </label>
      <div className="acx-list__items" role="listbox">
        {failed ? (
          <SnippetLoadError className="acx-list__empty" onRetry={() => setAttempt((n) => n + 1)} />
        ) : snippets === null ? (
          <div className="acx-list__empty">Loading…</div>
        ) : shown.length ? (
          shown.map((s) => (
            <button
              key={s.id}
              type="button"
              role="option"
              aria-selected={false}
              className="acx-list__item sn-pick__item"
              onMouseEnter={() => setHovered(s.id)}
              onFocus={() => setHovered(s.id)}
              onClick={() => void pick(s)}
            >
              <span className="sn-pick__name">{s.name}</span>
              <span className="sn-pick__shortcut">#{s.shortcut}</span>
            </button>
          ))
        ) : (
          <div className="acx-list__empty">
            {snippets.length ? 'No snippets match your search' : 'No snippets yet'}
          </div>
        )}
      </div>
      {previewed && !failed ? (
        <div className="sn-pick__preview" aria-live="polite">
          <strong>{previewed.name}</strong>
          <p>{snippetPlainText(previewed.bodyHtml)}</p>
        </div>
      ) : null}
    </AnchoredPopover>
  );
}
