import React from 'react';

/**
 * Props for the MarkdownMessage component.
 */
interface MarkdownMessageProps {
  /** Raw markdown content to render */
  content: string;
  /** Custom CSS classes for the container */
  className?: string;
}

/**
 * Lightweight Markdown Parser and Renderer.
 *
 * @description
 * A simplified markdown renderer that converts basic syntax (Headers, Bold, Italic,
 * Links, Inline Code, Lists) into sanitized HTML. Optimized for chat messages
 * where a full-blown parser might be overkill.
 *
 * @ai-rules
 * 1. Sanitization: Uses regex for conversion. Be cautious with complex markdown structures.
 * 2. Styling: Injected HTML uses specific Tailwind classes for consistent typography.
 * 3. Security: Uses `dangerouslySetInnerHTML`. Ensure `content` source is trusted or pre-sanitized if necessary.
 */
export function MarkdownMessage({ content, className = '' }: MarkdownMessageProps) {
  // Convert simple Markdown to HTML
  const convertMarkdownToHtml = (markdown: string): string => {
    let html = markdown;

    // Escape existing HTML
    html = html.replace(/</g, '<').replace(/>/g, '>');

    // Headers (large to small to avoid conflicts)
    html = html.replace(
      /^### (.*$)/gim,
      '<h3 class="font-medium text-sm mt-2 mb-1 break-words">$1</h3>'
    );
    html = html.replace(
      /^## (.*$)/gim,
      '<h2 class="font-medium text-base mt-3 mb-1.5 break-words">$1</h2>'
    );
    html = html.replace(
      /^# (.*$)/gim,
      '<h1 class="font-medium text-lg mt-3 mb-2 break-words">$1</h1>'
    );

    // Bold
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="font-medium">$1</strong>');

    // Italic
    html = html.replace(/\*(.*?)\*/g, '<em class="italic">$1</em>');

    // Links
    html = html.replace(
      /\[([^\]]+)\]\(([^)]+)\)/g,
      '<a href="$2" class="text-[var(--chart-4)] hover:underline break-all" target="_blank" rel="noopener noreferrer">$1</a>'
    );

    // Code inline
    html = html.replace(
      /`([^`]+)`/g,
      '<code class="px-1.5 py-0.5 rounded bg-muted text-xs font-mono break-all inline-block max-w-full">$1</code>'
    );

    // Unordered lists (bullet points) - properly wrap in ul
    html = html.replace(/((?:^[•\-] .*$(?:\n|$))+)/gim, match => {
      const items = match
        .trim()
        .split('\n')
        .map(
          item =>
            `<li class="ml-4 mb-1 list-disc break-words">${item.replace(/^[•\-]\s+/, '')}</li>`
        )
        .join('');
      return `<ul class="list-disc my-2">${items}</ul>`;
    });

    // Ordered lists - properly wrap in ol
    html = html.replace(/((?:^\d+\. .*$(?:\n|$))+)/gim, match => {
      const items = match
        .trim()
        .split('\n')
        .map(
          item =>
            `<li class="ml-4 mb-1 list-decimal break-words">${item.replace(/^\d+\.\s+/, '')}</li>`
        )
        .join('');
      return `<ol class="list-decimal my-2">${items}</ol>`;
    });

    // GFM Tables — must run before line-break transforms
    html = html.replace(/((?:^\|.+\|[ \t]*(?:\r?\n|$))+)/gm, match => {
      const rows = match
        .trim()
        .split(/\r?\n/)
        .filter(line => line.trim());
      if (rows.length < 2) return match;

      const isSeparatorRow = /^\|[\s\-:|]+\|$/.test(rows[1].trim());
      if (!isSeparatorRow) return match;

      const parseCells = (row: string) =>
        row
          .split('|')
          .slice(1, -1)
          .map(cell => cell.trim());

      const headerCells = parseCells(rows[0])
        .map(
          cell =>
            `<th class="px-3 py-2 text-left font-medium text-xs uppercase tracking-wide border-b border-border">${cell}</th>`
        )
        .join('');

      const bodyRows = rows
        .slice(2)
        .map(
          row =>
            `<tr class="border-b border-border last:border-0 hover:bg-muted/50">${parseCells(row)
              .map(cell => `<td class="px-3 py-2 text-sm">${cell}</td>`)
              .join('')}</tr>`
        )
        .join('');

      return `<div class="overflow-x-auto my-3 rounded-[var(--radius)] border border-border"><table class="w-full text-sm"><thead class="bg-muted/50"><tr>${headerCells}</tr></thead><tbody>${bodyRows}</tbody></table></div>`;
    });

    // Emojis and icons (keep as is)

    // Line breaks (preserve double line breaks as paragraphs)
    html = html.replace(/\n\n/g, '</p><p class="mb-2 break-words">');
    html = html.replace(/\n/g, '<br/>');

    // Wrap in initial paragraph
    html = '<p class="mb-2 break-words">' + html + '</p>';

    // Clean up empty paragraphs
    html = html.replace(/<p[^>]*>\s*<\/p>/g, '');

    return html;
  };

  const htmlContent = convertMarkdownToHtml(content);

  return (
    <div
      className={`text-sm leading-relaxed break-words overflow-wrap-anywhere max-w-full ${className}`}
      dangerouslySetInnerHTML={{ __html: htmlContent }}
    />
  );
}
