import React from 'react';
import { View, Text } from '@tarojs/components';
import './MarkdownRenderer.scss';

interface MarkdownRendererProps {
  content: string;
  className?: string;
}

/**
 * 简单的Markdown渲染器
 * 支持常用的Markdown语法
 */
const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, className = '' }) => {

  // 解析Markdown内容
  const parseMarkdown = (text: string) => {
    if (!text) return [];

    const lines = text.split('\n');
    const elements: JSX.Element[] = [];
    let currentIndex = 0;

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const trimmedLine = line.trim();

      // 空行
      if (!trimmedLine) {
        elements.push(<View key={`empty-${currentIndex++}`} className="markdown-br" />);
        continue;
      }

      // 标题 (# ## ###)
      if (trimmedLine.startsWith('#')) {
        const level = trimmedLine.match(/^#+/)?.[0].length || 1;
        const title = trimmedLine.replace(/^#+\s*/, '');
        elements.push(
          <View key={`heading-${currentIndex++}`} className={`markdown-heading markdown-h${level}`}>
            <Text>{title}</Text>
          </View>
        );
        continue;
      }

      // 代码块 (```)
      if (trimmedLine.startsWith('```')) {
        const codeLines: string[] = [];
        i++; // 跳过开始的```

        while (i < lines.length && !lines[i].trim().startsWith('```')) {
          codeLines.push(lines[i]);
          i++;
        }

        elements.push(
          <View key={`code-block-${currentIndex++}`} className="markdown-code-block">
            <Text className="markdown-code-text">{codeLines.join('\n')}</Text>
          </View>
        );
        continue;
      }

      // 列表项 (- * +)
      if (/^[-*+]\s/.test(trimmedLine)) {
        const listItem = trimmedLine.replace(/^[-*+]\s/, '');
        elements.push(
          <View key={`list-${currentIndex++}`} className="markdown-list-item">
            <Text className="markdown-bullet">•</Text>
            <Text className="markdown-list-text">{parseInlineMarkdown(listItem)}</Text>
          </View>
        );
        continue;
      }

      // 数字列表 (1. 2. 3.)
      if (/^\d+\.\s/.test(trimmedLine)) {
        const match = trimmedLine.match(/^(\d+)\.\s(.*)$/);
        if (match) {
          const [, number, listItem] = match;
          elements.push(
            <View key={`ordered-list-${currentIndex++}`} className="markdown-ordered-list-item">
              <Text className="markdown-number">{number}.</Text>
              <Text className="markdown-list-text">{parseInlineMarkdown(listItem)}</Text>
            </View>
          );
        }
        continue;
      }

      // 引用 (>)
      if (trimmedLine.startsWith('>')) {
        const quote = trimmedLine.replace(/^>\s*/, '');
        elements.push(
          <View key={`quote-${currentIndex++}`} className="markdown-blockquote">
            <Text className="markdown-quote-text">{parseInlineMarkdown(quote)}</Text>
          </View>
        );
        continue;
      }

      // 普通段落
      elements.push(
        <View key={`paragraph-${currentIndex++}`} className="markdown-paragraph">
          <Text className="markdown-text">{parseInlineMarkdown(trimmedLine)}</Text>
        </View>
      );
    }

    return elements;
  };

  // 解析行内Markdown语法
  const parseInlineMarkdown = (text: string): JSX.Element[] => {
    if (!text) return [<Text key="empty"></Text>];

    const parts: JSX.Element[] = [];
    let remaining = text;
    let keyIndex = 0;

    // 创建一个简单的解析器
    const parseSegment = (segment: string): JSX.Element[] => {
      const result: JSX.Element[] = [];
      let current = segment;

      // 处理行内代码 `code`
      current = current.replace(/`([^`]+)`/g, (match, code) => {
        result.push(
          <Text key={`code-${keyIndex++}`} className="markdown-inline-code">
            {code}
          </Text>
        );
        return `__PLACEHOLDER_${result.length - 1}__`;
      });

      // 处理粗体 **text**
      current = current.replace(/\*\*([^*]+)\*\*/g, (match, text) => {
        result.push(
          <Text key={`bold-${keyIndex++}`} className="markdown-bold">
            {text}
          </Text>
        );
        return `__PLACEHOLDER_${result.length - 1}__`;
      });

      // 处理斜体 *text*
      current = current.replace(/\*([^*]+)\*/g, (match, text) => {
        result.push(
          <Text key={`italic-${keyIndex++}`} className="markdown-italic">
            {text}
          </Text>
        );
        return `__PLACEHOLDER_${result.length - 1}__`;
      });

      // 处理链接 [text](url)
      current = current.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, linkText, url) => {
        result.push(
          <Text key={`link-${keyIndex++}`} className="markdown-link">
            {linkText}
          </Text>
        );
        return `__PLACEHOLDER_${result.length - 1}__`;
      });

      // 分割并重组
      const finalParts = current.split(/(__PLACEHOLDER_\d+__)/);
      const finalResult: JSX.Element[] = [];

      finalParts.forEach((part, index) => {
        if (part.startsWith('__PLACEHOLDER_')) {
          const placeholderIndex = parseInt(part.match(/\d+/)?.[0] || '0');
          if (result[placeholderIndex]) {
            finalResult.push(result[placeholderIndex]);
          }
        } else if (part) {
          finalResult.push(<Text key={`text-${keyIndex++}`}>{part}</Text>);
        }
      });

      return finalResult.length > 0 ? finalResult : [<Text key={`default-${keyIndex++}`}>{segment}</Text>];
    };

    return parseSegment(remaining);
  };

  const renderedContent = parseMarkdown(content);

  return (
    <View className={`markdown-renderer ${className}`}>
      {renderedContent}
    </View>
  );
};

export default MarkdownRenderer;
