'use client';

import Image from 'next/image';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

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

/**
 * Generate a URL-friendly ID from a heading text
 */
function slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '') // Remove special characters
    .replace(/[\s_-]+/g, '-') // Replace spaces and underscores with hyphens
    .replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}

/**
 * Extract text content from React children (handles nested structures)
 */
function extractTextFromChildren(children: React.ReactNode): string {
  if (typeof children === 'string') {
    return children;
  }
  if (Array.isArray(children)) {
    return children.map((child) => extractTextFromChildren(child)).join('');
  }
  if (children && typeof children === 'object' && 'props' in children && children.props && typeof children.props === 'object' && 'children' in children.props) {
    return extractTextFromChildren(children.props.children as React.ReactNode);
  }
  return '';
}

export default function MarkdownRenderer({ content, className = '' }: MarkdownRendererProps) {
  return (
    <div className={className}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          // Headings with IDs for table of contents
          h1: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h1 id={id} className="text-3xl md:text-4xl font-bold text-gray-900 mb-6" {...props}>{children}</h1>;
          },
          h2: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h2 id={id} className="text-2xl font-semibold text-gray-900 mb-4" {...props}>{children}</h2>;
          },
          h3: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h3 id={id} className="text-xl font-semibold text-gray-900 mb-3" {...props}>{children}</h3>;
          },
          h4: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h4 id={id} className="text-lg font-semibold text-gray-900 mb-2" {...props}>{children}</h4>;
          },
          h5: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h5 id={id} className="text-base font-semibold text-gray-900 mb-2" {...props}>{children}</h5>;
          },
          h6: ({ children, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => {
            const text = extractTextFromChildren(children);
            const id = slugify(text);
            return <h6 id={id} className="text-sm font-semibold text-gray-900 mb-2" {...props}>{children}</h6>;
          },
          
          // Paragraphs and text
          p: (props: React.HTMLAttributes<HTMLParagraphElement>) => (
            <p className="text-gray-700 leading-relaxed mb-4 last:mb-0" {...props} />
          ),
          strong: (props: React.HTMLAttributes<HTMLElement>) => (
            <strong className="font-semibold text-gray-900" {...props} />
          ),
          em: (props: React.HTMLAttributes<HTMLElement>) => (
            <em className="italic text-gray-700" {...props} />
          ),

          
          // Lists
          ul: (props: React.HTMLAttributes<HTMLUListElement>) => (
            <ul className="list-disc list-inside space-y-1 mb-4 last:mb-0" {...props} />
          ),
          ol: (props: React.HTMLAttributes<HTMLOListElement>) => (
            <ol className="list-decimal list-inside space-y-1 mb-4 last:mb-0" {...props} />
          ),
          li: (props: React.HTMLAttributes<HTMLLIElement>) => (
            <li className="text-gray-700 leading-relaxed" {...props} />
          ),
          
          // Blockquotes
          blockquote: (props: React.HTMLAttributes<HTMLQuoteElement>) => (
            <blockquote className="border-l-4 border-blue-500 pl-4 italic text-gray-600 bg-blue-50 py-2 mb-4" {...props} />
          ),
          
          // Links
          a: (props: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
            <a className="text-blue-600 hover:text-blue-800 hover:underline" {...props} />
          ),
          
          // Images
          img: (props: React.ImgHTMLAttributes<HTMLImageElement>) => {
            const { src, alt, width, height, ...restProps } = props;
            if (!src || typeof src !== 'string') return null;
            return (
              <Image 
                src={src} 
                alt={alt || ""} 
                width={typeof width === 'number' ? width : 800} 
                height={typeof height === 'number' ? height : 600} 
                className="max-w-full h-auto rounded-lg shadow-md my-4" 
                {...restProps} 
              />
            );
          },
          
          // Horizontal rules
          hr: () => <hr className="my-6 border-gray-200" />,
          
          // Tables
          table: (props: React.HTMLAttributes<HTMLTableElement>) => (
            <div className="overflow-x-auto my-4">
              <table className="min-w-full bg-white border border-gray-200 rounded-lg" {...props} />
            </div>
          ),
          thead: (props: React.HTMLAttributes<HTMLTableSectionElement>) => (
            <thead className="bg-gray-50" {...props} />
          ),
          tbody: (props: React.HTMLAttributes<HTMLTableSectionElement>) => (
            <tbody {...props} />
          ),
          tr: (props: React.HTMLAttributes<HTMLTableRowElement>) => (
            <tr className="border-b border-gray-200" {...props} />
          ),
          th: (props: React.HTMLAttributes<HTMLTableCellElement>) => (
            <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900" {...props} />
          ),
          td: (props: React.HTMLAttributes<HTMLTableCellElement>) => (
            <td className="px-4 py-3 text-sm text-gray-700" {...props} />
          ),
          
          // Code blocks
          pre: (props: React.HTMLAttributes<HTMLPreElement>) => (
            <pre className="bg-gray-100 p-4 rounded-lg overflow-x-auto my-4" {...props} />
          ),
          
          // Code
          code: (props: React.HTMLAttributes<HTMLElement>) => (
            <code className="bg-gray-100 px-1.5 py-0.5 rounded text-sm font-mono text-gray-800" {...props} />
          ),
        }}
      >
        {content}
      </ReactMarkdown>
    </div>
  );
}
