'use client';

import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import type { SnippetTarget } from '@/features/snippets/api.client';
import { useEditableSnippetHash } from '@/features/snippets/ui/useSnippetHash';
import { cn } from '@/lib/utils/cn';

/**
 * Rich-text notes (QA #648; design components/rich-notes.js, Meetings spec 2): the meeting
 * notes editor. A 36px toolbar above the text with Bold, Italic, Bullet List and Insert Link,
 * tooltips with their shortcuts (Cmd on a Mac, Ctrl elsewhere), the button of the format under
 * the caret shown on, and a small popover to add, edit or remove a link. Pasting keeps only the
 * text. `onChange` gets the HTML ("" when empty); `openKey` reloads `value` into the editor.
 */

const MAC_RE = /Mac|iPhone|iPad/;
const noSubscribe = () => () => {};
const isMac = () => MAC_RE.test(navigator.platform || navigator.userAgent);

type Cmd = 'bold' | 'italic' | 'insertUnorderedList' | 'link';
type Active = Record<Cmd, boolean>;
const NONE: Active = { bold: false, italic: false, insertUnorderedList: false, link: false };

const BUTTONS: { cmd: Cmd; label: string; tip: (mod: string) => string; key?: string }[] = [
  { cmd: 'bold', label: 'Bold', tip: (mod) => `Bold (${mod}+B)`, key: 'b' },
  { cmd: 'italic', label: 'Italic', tip: (mod) => `Italic (${mod}+I)`, key: 'i' },
  { cmd: 'insertUnorderedList', label: 'Bullet List', tip: () => 'Bullet List' },
  { cmd: 'link', label: 'Insert Link', tip: (mod) => `Insert Link (${mod}+K)`, key: 'k' },
];

function ButtonFace({ cmd }: { cmd: Cmd }) {
  if (cmd === 'bold') return <b>B</b>;
  if (cmd === 'italic') return <i>I</i>;
  if (cmd === 'insertUnorderedList')
    return (
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        aria-hidden
      >
        <path d="M9 6h11M9 12h11M9 18h11" />
        <circle cx="4.5" cy="6" r="1" fill="currentColor" />
        <circle cx="4.5" cy="12" r="1" fill="currentColor" />
        <circle cx="4.5" cy="18" r="1" fill="currentColor" />
      </svg>
    );
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7" />
      <path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" />
    </svg>
  );
}

/** The design's link check: no script URLs, and a bare host gets https://. "" when unusable. */
export function safeNotesUrl(value: string): string {
  const s = value.trim();
  if (!s) return '';
  if (/^(javascript|data|vbscript):/i.test(s)) return '';
  return /^[a-z][a-z0-9+.-]*:/i.test(s) ? s : `https://${s}`;
}

/** No visible text and no list item or image: the placeholder shows. */
function areaIsEmpty(area: HTMLElement): boolean {
  return !area.textContent?.trim() && !area.querySelector('li, img');
}

export function RichNotes({
  openKey,
  value,
  onChange,
  label,
  placeholder,
  minHeight,
  snippetTarget,
}: {
  openKey: number | string;
  value: string;
  onChange: (html: string) => void;
  label: string;
  placeholder?: string;
  /** The design's text area is 110px tall; smaller in compact forms. */
  minHeight?: number;
  /** HUB-417: "#shortcut" snippets in these notes, filled for these records. Off when unset. */
  snippetTarget?: SnippetTarget;
}) {
  const areaRef = useRef<HTMLDivElement>(null);
  const hash = useEditableSnippetHash(areaRef, {
    target: snippetTarget ?? {},
    off: !snippetTarget,
  });
  const popRef = useRef<HTMLDivElement>(null);
  const barRef = useRef<HTMLDivElement>(null);
  const linkTextRef = useRef<HTMLInputElement>(null);
  const linkUrlRef = useRef<HTMLInputElement>(null);
  const saved = useRef<Range | null>(null);
  const editLink = useRef<HTMLAnchorElement | null>(null);
  const [empty, setEmpty] = useState(true);
  const [active, setActive] = useState<Active>(NONE);
  const [linkOpen, setLinkOpen] = useState(false);
  const [linkText, setLinkText] = useState('');
  const [linkUrl, setLinkUrl] = useState('');
  const [linkInvalid, setLinkInvalid] = useState(false);
  const [editing, setEditing] = useState(false);
  const mod = useSyncExternalStore(
    noSubscribe,
    () => (isMac() ? 'Cmd' : 'Ctrl'),
    () => 'Ctrl',
  );

  useEffect(() => {
    const area = areaRef.current;
    if (!area) return;
    area.innerHTML = value || '';
    setEmpty(areaIsEmpty(area));
    setLinkOpen(false);
    // Only a new `openKey` reloads the editor; typing keeps its own DOM.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [openKey]);

  const inside = (node: Node | null) => {
    const area = areaRef.current;
    return !!node && !!area && (node === area || area.contains(node));
  };
  const linkAt = (): HTMLAnchorElement | null => {
    const area = areaRef.current;
    let n: Node | null = window.getSelection()?.anchorNode ?? null;
    while (n && n !== area) {
      if (n instanceof HTMLAnchorElement) return n;
      n = n.parentNode;
    }
    return null;
  };

  const syncState = useCallback(() => {
    const sel = window.getSelection();
    const on = !!sel?.rangeCount && inside(sel.anchorNode);
    const state = (cmd: string) => {
      try {
        return on && document.queryCommandState(cmd);
      } catch {
        return false;
      }
    };
    setActive({
      bold: state('bold'),
      italic: state('italic'),
      insertUnorderedList: state('insertUnorderedList'),
      link: on && !!linkAt(),
    });
    // inside/linkAt only read refs.
  }, []);

  const changed = () => {
    const area = areaRef.current;
    if (!area) return;
    const isEmpty = areaIsEmpty(area);
    if (isEmpty && area.innerHTML !== '') area.innerHTML = '';
    setEmpty(isEmpty);
    syncState();
    onChange(area.innerHTML);
  };

  useEffect(() => {
    const onSelection = () => {
      if (document.activeElement === areaRef.current) syncState();
    };
    document.addEventListener('selectionchange', onSelection);
    return () => document.removeEventListener('selectionchange', onSelection);
  }, [syncState]);

  // A click outside the link box (and the toolbar) closes it.
  useEffect(() => {
    if (!linkOpen) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!popRef.current?.contains(t) && !barRef.current?.contains(t)) setLinkOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [linkOpen]);

  const saveSelection = () => {
    const sel = window.getSelection();
    if (sel?.rangeCount && inside(sel.anchorNode)) saved.current = sel.getRangeAt(0).cloneRange();
  };
  const restoreSelection = () => {
    areaRef.current?.focus();
    const sel = window.getSelection();
    if (saved.current && sel) {
      sel.removeAllRanges();
      sel.addRange(saved.current);
    }
  };

  const openLink = () => {
    saveSelection();
    const a = linkAt();
    editLink.current = a;
    const sel = window.getSelection();
    const text = a
      ? (a.textContent ?? '')
      : sel?.rangeCount && inside(sel.anchorNode)
        ? sel.toString()
        : '';
    setLinkText(text);
    setLinkUrl(a?.getAttribute('href') ?? '');
    setLinkInvalid(false);
    setEditing(!!a);
    setLinkOpen(true);
    window.setTimeout(() => (text ? linkUrlRef.current : linkTextRef.current)?.focus(), 0);
  };
  const closeLink = (back: boolean) => {
    setLinkOpen(false);
    if (back) restoreSelection();
  };
  const applyLink = () => {
    const url = safeNotesUrl(linkUrl);
    if (!url) {
      setLinkInvalid(true);
      linkUrlRef.current?.focus();
      return;
    }
    setLinkInvalid(false);
    const text = linkText.trim() || url;
    closeLink(true);
    const current = editLink.current;
    if (current) {
      current.setAttribute('href', url);
      current.textContent = text;
    } else {
      const a = document.createElement('a');
      a.href = url;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
      a.textContent = text;
      const sel = window.getSelection();
      if (sel?.rangeCount && inside(sel.anchorNode)) {
        const r = sel.getRangeAt(0);
        r.deleteContents();
        r.insertNode(a);
        r.setStartAfter(a);
        r.collapse(true);
        sel.removeAllRanges();
        sel.addRange(r);
      } else {
        areaRef.current?.appendChild(a);
      }
    }
    changed();
  };
  const removeLink = () => {
    const a = editLink.current;
    closeLink(true);
    if (a) a.replaceWith(document.createTextNode(a.textContent ?? ''));
    changed();
  };

  const run = (cmd: Cmd) => {
    if (cmd === 'link') {
      openLink();
      return;
    }
    areaRef.current?.focus();
    try {
      document.execCommand(cmd, false);
    } catch {
      // unsupported
    }
    changed();
  };

  return (
    <div className="rn">
      <div className="rn__bar" role="toolbar" aria-label="Text formatting" ref={barRef}>
        {BUTTONS.map((b) => (
          <button
            key={b.cmd}
            type="button"
            className={cn('rn__btn', active[b.cmd] && 'is-active')}
            aria-label={b.label}
            aria-pressed={active[b.cmd]}
            data-tip={b.tip(mod)}
            // Keeps the selection in the editor.
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => run(b.cmd)}
          >
            <ButtonFace cmd={b.cmd} />
          </button>
        ))}
      </div>
      <div
        ref={areaRef}
        className={cn('rn__area', empty && 'is-empty')}
        contentEditable
        suppressContentEditableWarning
        role="textbox"
        aria-multiline="true"
        aria-label={label}
        data-placeholder={placeholder}
        style={minHeight ? { minHeight } : undefined}
        onInput={() => {
          changed();
          hash.track();
        }}
        onBlur={hash.close}
        onKeyDown={(e) => {
          if (hash.onKeyDown(e)) {
            e.preventDefault();
            return;
          }
          if (!(e.metaKey || e.ctrlKey) || e.altKey) return;
          const b = BUTTONS.find((x) => x.key === e.key.toLowerCase());
          if (!b) return;
          e.preventDefault();
          run(b.cmd);
        }}
        onPaste={(e) => {
          // Paste as plain text so outside styling does not come along.
          const text = e.clipboardData.getData('text/plain');
          e.preventDefault();
          document.execCommand('insertText', false, text);
        }}
        onClick={(e) => {
          // Links open with Cmd/Ctrl + click while editing.
          const a = (e.target as HTMLElement).closest('a');
          if (a && (e.metaKey || e.ctrlKey)) window.open(a.href, '_blank', 'noopener');
        }}
      />
      {hash.list}
      <div
        ref={popRef}
        className="rn__link"
        role="dialog"
        aria-label="Insert link"
        hidden={!linkOpen}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            applyLink();
          }
          if (e.key === 'Escape') {
            e.stopPropagation();
            closeLink(true);
          }
        }}
      >
        <label className="rn__link-row">
          <span>Text</span>
          <input
            ref={linkTextRef}
            type="text"
            placeholder="Link text"
            // Off while closed, so a half-typed URL never blocks the surrounding form.
            disabled={!linkOpen}
            value={linkText}
            onChange={(e) => setLinkText(e.target.value)}
          />
        </label>
        <label className="rn__link-row">
          <span>URL</span>
          <input
            ref={linkUrlRef}
            type="url"
            placeholder="https://"
            disabled={!linkOpen}
            value={linkUrl}
            aria-invalid={linkInvalid || undefined}
            onChange={(e) => setLinkUrl(e.target.value)}
          />
        </label>
        <div className="rn__link-acts">
          <button type="button" className="rn__lbtn rn__lbtn--primary" onClick={applyLink}>
            Apply
          </button>
          <button type="button" className="rn__lbtn" hidden={!editing} onClick={removeLink}>
            Remove link
          </button>
          <button type="button" className="rn__lbtn" onClick={() => closeLink(true)}>
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
