import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

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

export function MarkdownRenderer({ content, className = '' }: MarkdownRendererProps) {
	return (
		<div className={`prose prose-sm max-w-none ${className}`}>
			<ReactMarkdown
				remarkPlugins={[remarkGfm]}
				components={{
					h1: ({ node, ...props }) => (
						<h1 className='text-2xl font-bold mb-4 mt-6 text-text-primary' {...props} />
					),
					h2: ({ node, ...props }) => (
						<h2 className='text-xl font-semibold mb-3 mt-5 text-text-primary' {...props} />
					),
					h3: ({ node, ...props }) => (
						<h3 className='text-lg font-semibold mb-2 mt-4 text-text-primary' {...props} />
					),
					p: ({ node, ...props }) => <p className='mb-3 text-text-primary' {...props} />,
					ul: ({ node, ...props }) => <ul className='list-disc list-inside mb-3 space-y-1' {...props} />,
					ol: ({ node, ...props }) => <ol className='list-decimal list-inside mb-3 space-y-1' {...props} />,
					li: ({ node, ...props }) => <li className='text-text-primary' {...props} />,
					code: ({ node, inline, ...props }: any) =>
						inline ? (
							<code
								className='bg-bg-secondary px-1.5 py-0.5 rounded text-sm font-mono text-text-primary'
								{...props}
							/>
						) : (
							<code
								className='block bg-bg-secondary p-3 rounded-lg overflow-x-auto text-sm font-mono text-text-primary'
								{...props}
							/>
						),
					blockquote: ({ node, ...props }) => (
						<blockquote
							className='border-l-4 border-sidebar-bg pl-4 italic my-3 text-text-secondary'
							{...props}
						/>
					),
					a: ({ node, ...props }: any) => (
						<a
							className='text-sidebar-bg hover:underline'
							target='_blank'
							rel='noopener noreferrer'
							{...props}
						/>
					),
					strong: ({ node, ...props }) => <strong className='font-semibold text-text-primary' {...props} />,
					em: ({ node, ...props }) => <em className='italic' {...props} />,
					table: ({ node, ...props }) => (
						<div className='overflow-x-auto my-4'>
							<table className='min-w-full border-collapse border border-border' {...props} />
						</div>
					),
					thead: ({ node, ...props }) => <thead className='bg-bg-secondary' {...props} />,
					th: ({ node, ...props }) => (
						<th
							className='border border-border px-4 py-2 text-left font-semibold text-text-primary'
							{...props}
						/>
					),
					td: ({ node, ...props }) => (
						<td className='border border-border px-4 py-2 text-text-primary' {...props} />
					),
					hr: ({ node, ...props }) => <hr className='my-4 border-border' {...props} />,
				}}
			>
				{content}
			</ReactMarkdown>
		</div>
	);
}
