import React from 'react';
import CodeBlock from './CodeBlock';

interface RichTextRendererProps {
    content: string;
}

const parseInline = (text: string) => {
    const parts = text.split(/(\*\*.*?\*\*)/g);
    return parts.map((part, index) => {
        if (part.startsWith('**') && part.endsWith('**')) {
            return <strong key={index} style={{ color: 'white' }}>{part.slice(2, -2)}</strong>;
        }
        return part;
    });
};

const parseMarkdown = (text: string) => {
    const lines = text.split('\n');
    const elements: React.ReactNode[] = [];
    let currentListItems: React.ReactNode[] = [];

    lines.forEach((line, i) => {
        const trimmed = line.trim();
        if (trimmed.startsWith('* ') || trimmed.startsWith('- ')) {
            const content = trimmed.substring(2);
            currentListItems.push(
                <li key={`li-${i}`} style={{ marginBottom: '4px' }}>
                    {parseInline(content)}
                </li>
            );
        } else {
            if (currentListItems.length > 0) {
                elements.push(
                    <ul key={`ul-${i}`} style={{ paddingLeft: '20px', marginBottom: '16px', listStyleType: 'disc' }}>
                        {currentListItems}
                    </ul>
                );
                currentListItems = [];
            }
            if (trimmed.length > 0) {
                elements.push(
                    <p key={`p-${i}`} style={{ marginBottom: '16px' }}>
                        {parseInline(line)}
                    </p>
                );
            }
        }
    });

    if (currentListItems.length > 0) {
        elements.push(
            <ul key="ul-end" style={{ paddingLeft: '20px', marginBottom: '16px', listStyleType: 'disc' }}>
                {currentListItems}
            </ul>
        );
    }

    return elements;
};

const RichTextRenderer: React.FC<RichTextRendererProps> = ({ content }) => {
    if (!content) return null;

    const parts = content.split(/```/);

    return (
        <div className="rich-text-content">
            {parts.map((part, index) => {
                if (index % 2 === 1) {
                    // Code block
                    const firstLineBreak = part.indexOf('\n');
                    const language = part.slice(0, firstLineBreak).trim();
                    const code = part.slice(firstLineBreak + 1).trim();

                    return <CodeBlock key={index} language={language} code={code} />;
                }

                // Regular text with markdown parsing
                return (
                    <div key={index}>
                        {parseMarkdown(part)}
                    </div>
                );
            })}
        </div>
    );
};

export default RichTextRenderer;
