import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/button';
import { ChevronDown, ChevronUp } from 'lucide-react';

/**
 * Props for the FormattedDocument component.
 */
interface FormattedDocumentProps {
  /** The raw markdown string to be converted and displayed */
  content: string;
  /** Maximum number of characters to show in the collapsed preview state */
  maxPreviewLength?: number;
  /** Additional CSS classes for the container */
  className?: string;
}

/**
 * Simple Markdown-to-HTML formatter with collapsible preview.
 *
 * @description
 * Converts basic markdown syntax (headers, bold, lists, checkboxes) into styled
 * Tailwind HTML elements. Includes a "See more/less" toggle for long documents.
 *
 * @ai-rules
 * 1. Use this component to display AI-generated text or documentation strings.
 * 2. It supports standard markdown symbols: #, ##, ###, **, *, -, [ ], [x].
 * 3. `maxPreviewLength` defaults to 500 characters.
 */
export function FormattedDocument({
  content,
  maxPreviewLength = 500,
  className = '',
}: FormattedDocumentProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const { t } = useTranslation();

  /**
   * Converts simple Markdown strings to HTML using regex patterns.
   */
  const convertMarkdownToHtml = (markdown: string): string => {
    let html = markdown;

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

    // Headers (with improved styling, reduced spacing)
    html = html.replace(
      /^### (.*$)/gim,
      '<h3 class="text-base font-medium mt-2 mb-1 text-foreground">$1</h3>'
    );
    html = html.replace(
      /^## (.*$)/gim,
      '<h2 class="text-lg font-medium mt-2 mb-1 text-foreground">$1</h2>'
    );
    html = html.replace(
      /^# (.*$)/gim,
      '<h1 class="text-xl font-medium mt-3 mb-2 text-foreground">$1</h1>'
    );

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

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

    // Checkboxes (Process before lists to avoid collisions)
    html = html.replace(
      /^[-*+] \[ \] (.*$)/gim,
      '<div class="flex items-center gap-2 ml-4 my-0.5"><input type="checkbox" disabled class="rounded w-3.5 h-3.5 accent-primary" aria-label="$1" /> <span class="text-sm">$1</span></div>'
    );
    html = html.replace(
      /^[-*+] \[x\] (.*$)/gim,
      '<div class="flex items-center gap-2 ml-4 my-0.5"><input type="checkbox" checked disabled class="rounded w-3.5 h-3.5 accent-primary" aria-label="$1" /> <span class="text-sm">$1</span></div>'
    );

    // Lists (Bullet and Numbered) - Wrap blocks of items in ul/ol
    html = html.replace(/((?:^[-*+] .*$(?:\n|$))+)/gim, match => {
      const items = match
        .trim()
        .split('\n')
        .map(item => `<li class="ml-6 my-0.5 list-disc">${item.replace(/^[-*+] /i, '')}</li>`)
        .join('');
      return `<ul class="list-disc my-2">${items}</ul>`;
    });

    html = html.replace(/((?:^\d+\. .*$(?:\n|$))+)/gim, match => {
      const items = match
        .trim()
        .split('\n')
        .map(item => `<li class="ml-6 my-0.5 list-decimal">${item.replace(/^\d+\. /i, '')}</li>`)
        .join('');
      return `<ol class="list-decimal my-2">${items}</ol>`;
    });

    // Horizontal rule
    html = html.replace(/^---$/gim, '<hr class="my-2 border-border" />');

    // Line breaks - treat single \n as space, \n\n as paragraph break
    html = html.replace(/\n\n+/g, '</p><p class="my-0.5">');
    html = html.replace(/\n/g, ' ');

    // Wrap in paragraph
    html = '<p class="my-0.5">' + html + '</p>';

    return html;
  };

  const htmlContent = convertMarkdownToHtml(content);
  const isLong = content.length > maxPreviewLength;

  // If not long or if expanded, show everything
  const displayContent =
    !isLong || isExpanded
      ? htmlContent
      : convertMarkdownToHtml(content.substring(0, maxPreviewLength) + '...');

  return (
    <div className={className}>
      <div
        className="max-w-none text-sm text-foreground leading-relaxed break-words overflow-hidden"
        dangerouslySetInnerHTML={{ __html: displayContent }}
      />

      {isLong && (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsExpanded(!isExpanded)}
          className="mt-2 w-full text-xs hover:bg-accent text-muted-foreground"
        >
          {isExpanded ? (
            <>
              <ChevronUp className="w-3 h-3 mr-1" />
              {t('common.seeLess')}
            </>
          ) : (
            <>
              <ChevronDown className="w-3 h-3 mr-1" />
              {t('common.seeMore')}
            </>
          )}
        </Button>
      )}
    </div>
  );
}
