import { markdownEngine, rules, type MarkdownNode } from '@cloudrac3r/discord-markdown';
import type { Emote } from './emotes';
import type { Mention } from './mentions';

function escapeHtml(text: string): string {
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function escapeRegExp(text: string): string {
  return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function mentionLinker(mentions: Mention[]): (escaped: string) => string {
  const byText = new Map(mentions.filter((m) => m.text).map((m) => [escapeHtml(m.text), m.user_id]));
  if (byText.size === 0) return (escaped) => escaped;
  const names = [...byText.keys()].sort((a, b) => b.length - a.length);
  const pattern = new RegExp(names.map(escapeRegExp).join('|'), 'g');
  return (escaped) =>
    escaped.replace(pattern, (name) => `<a href="https://matrix.to/#/${escapeHtml(byText.get(name)!)}">${name}</a>`);
}

function emoteLinker(emotes: Emote[]): (escaped: string) => string {
  if (emotes.length === 0) return (escaped) => escaped;
  const byCode = new Map(emotes.map((e) => [e.shortcode, e.mxc]));
  return (escaped) =>
    escaped.replace(/:([\w+-]+):/g, (whole, code: string) => {
      const mxc = byCode.get(code);
      return mxc ? `<img data-mx-emoticon src="${escapeHtml(mxc)}" alt="${whole}" title="${whole}" height="32">` : whole;
    });
}

function textToHtml(text: string, link: (escaped: string) => string): string {
  return link(escapeHtml(text)).replace(/\n/g, '<br>');
}

const parseMarkdown = markdownEngine.parserFor(
  Object.fromEntries(Object.entries(rules).filter(([name]) => !name.startsWith('discord')))
);
const INLINE_TAGS: Record<string, string> = { em: 'em', strong: 'strong', u: 'u', strike: 'del', small: 'sub' };
const BLOCK_TYPES = new Set(['blockQuote', 'codeBlock', 'heading', 'list', 'paragraph']);

function renderMarkdown(nodes: MarkdownNode[], link: (escaped: string) => string): string {
  let html = '';
  let text = '';
  const flushText = () => {
    html += textToHtml(text, link);
    text = '';
  };
  for (const node of nodes) {
    if (node.type === 'text') {
      text += node.content;
      continue;
    }
    flushText();
    const children = () => renderMarkdown(node.content, link);
    const tag = INLINE_TAGS[node.type];
    if (tag) {
      html += `<${tag}>${children()}</${tag}>`;
      continue;
    }
    switch (node.type) {
      case 'br':
      case 'newline':
        html += '<br>';
        break;
      case 'inlineCode':
        html += `<code>${escapeHtml(node.content)}</code>`;
        break;
      case 'codeBlock': {
        const lang = /^[\w+#-]+$/.test(node.lang ?? '') ? ` class="language-${escapeHtml(node.lang)}"` : '';
        html += `<pre><code${lang}>${escapeHtml(node.content)}\n</code></pre>`;
        break;
      }
      case 'spoiler':
        html += `<span data-mx-spoiler>${renderMarkdown(node.parsed, link)}</span>`;
        break;
      case 'blockQuote':
        html += `<blockquote>${children()}</blockquote>`;
        break;
      case 'paragraph':
        html += `<p>${children()}</p>`;
        break;
      case 'heading': {
        const level = Math.max(1, Math.min(6, node.level));
        html += `<h${level}>${children()}</h${level}>`;
        break;
      }
      case 'list': {
        const tag = node.ordered ? 'ol' : 'ul';
        const start = node.ordered && Number.isSafeInteger(node.start) && node.start > 0 ? ` start="${node.start}"` : '';
        html += `<${tag}${start}>${node.items.map((item: MarkdownNode[]) => `<li>${renderMarkdown(item, link)}</li>`).join('')}</${tag}>`;
        break;
      }
      case 'link':
      case 'url':
      case 'autolink': {
        const label = renderMarkdown(node.content, (escaped) => escaped);
        const href = markdownEngine.sanitizeUrl(node.target);
        const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';
        html += href && /^(https?:|mailto:)/i.test(href) ? `<a href="${escapeHtml(href)}"${title}>${label}</a>` : label;
        break;
      }
    }
  }
  flushText();
  return html;
}

function markdownToHtml(body: string, link: (escaped: string) => string): string | null {
  const nodes = parseMarkdown(body, { inline: true });
  const html = renderMarkdown(nodes, link);
  if (html === textToHtml(body, (escaped) => escaped)) return null;
  if (nodes.every((node) => node.type === 'text' || node.type === 'br' || node.type === 'newline') ||
    nodes.some((node) => BLOCK_TYPES.has(node.type))) return html;
  return `<p>${html}</p>`;
}

/** Matrix `formatted_body` for a composed message, or null when plain text says it all. */
export function formatBody(body: string, mentions: Mention[], markdown: boolean, emotes: Emote[] = []): string | null {
  const mention = mentionLinker(mentions);
  const emote = emoteLinker(emotes);
  const link = (escaped: string) => emote(mention(escaped));
  const html = markdown ? markdownToHtml(body, link) : null;
  if (html !== null) return html;
  const plain = textToHtml(body, link);
  return plain === escapeHtml(body).replace(/\n/g, '<br>') ? null : plain;
}

export function insideOpenFence(text: string, caret: number): boolean {
  return (text.slice(0, caret).match(/^\s*```/gm)?.length ?? 0) % 2 === 1;
}
