import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import 'katex/dist/katex.min.css';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';

interface MarkdownRendererProps {
  content: string;
  className?: string;
  studyId?: string; // Optional study ID for resolving relative image paths
}

/**
 * Shared markdown renderer with syntax highlighting, GFM, and LaTeX support.
 * Used by both the Home page (README display) and Results page (reports).
 */
export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, className = '', studyId }) => {
  // Helper to resolve image URLs - converts relative paths to API endpoints
  const resolveImageSrc = (src: string | undefined): string => {
    if (!src) return '';

    // If it's already an absolute URL or data URL, return as-is
    if (src.startsWith('http://') || src.startsWith('https://') || src.startsWith('data:')) {
      return src;
    }

    // If we have a studyId, route through the API
    if (studyId) {
      // Remove leading ./ or / from the path
      const cleanPath = src.replace(/^\.?\//, '');
      return `/api/optimization/studies/${studyId}/image/${cleanPath}`;
    }

    // Fallback: return original src
    return src;
  };

  return (
    <article className={`markdown-body max-w-none ${className}`}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm, [remarkMath, { singleDollarTextMath: false }]]}
        rehypePlugins={[[rehypeKatex, { strict: false, trust: true, output: 'html' }]]}
        components={{
          // Custom heading styles
          h1: ({ children }) => (
            <h1 className="text-3xl font-bold text-white mb-6 pb-3 border-b border-dark-600">
              {children}
            </h1>
          ),
          h2: ({ children }) => (
            <h2 className="text-2xl font-semibold text-white mt-10 mb-4 pb-2 border-b border-dark-700">
              {children}
            </h2>
          ),
          h3: ({ children }) => (
            <h3 className="text-xl font-semibold text-white mt-8 mb-3">
              {children}
            </h3>
          ),
          h4: ({ children }) => (
            <h4 className="text-lg font-medium text-white mt-6 mb-2">
              {children}
            </h4>
          ),
          // Paragraphs
          p: ({ children }) => (
            <p className="text-dark-300 leading-relaxed mb-4">
              {children}
            </p>
          ),
          // Strong/Bold
          strong: ({ children }) => (
            <strong className="text-white font-semibold">{children}</strong>
          ),
          // Links
          a: ({ href, children }) => (
            <a
              href={href}
              className="text-primary-400 hover:text-primary-300 underline underline-offset-2"
              target="_blank"
              rel="noopener noreferrer"
            >
              {children}
            </a>
          ),
          // Lists
          ul: ({ children }) => (
            <ul className="list-disc list-inside text-dark-300 mb-4 space-y-1.5 ml-2">
              {children}
            </ul>
          ),
          ol: ({ children }) => (
            <ol className="list-decimal list-inside text-dark-300 mb-4 space-y-1.5 ml-2">
              {children}
            </ol>
          ),
          li: ({ children }) => (
            <li className="text-dark-300 leading-relaxed">{children}</li>
          ),
          // Code blocks with syntax highlighting
          code: ({ inline, className, children, ...props }: any) => {
            const match = /language-(\w+)/.exec(className || '');
            const language = match ? match[1] : '';

            if (!inline && language) {
              return (
                <div className="my-4 rounded-lg overflow-hidden border border-dark-600">
                  <div className="bg-dark-700 px-4 py-2 text-xs text-dark-400 font-mono border-b border-dark-600">
                    {language}
                  </div>
                  <SyntaxHighlighter
                    style={oneDark}
                    language={language}
                    PreTag="div"
                    customStyle={{
                      margin: 0,
                      padding: '1rem',
                      background: '#1a1d23',
                      fontSize: '0.875rem',
                    }}
                    {...props}
                  >
                    {String(children).replace(/\n$/, '')}
                  </SyntaxHighlighter>
                </div>
              );
            }

            if (!inline) {
              return (
                <pre className="my-4 p-4 bg-dark-700 rounded-lg border border-dark-600 overflow-x-auto">
                  <code className="text-primary-400 text-sm font-mono">{children}</code>
                </pre>
              );
            }

            return (
              <code className="px-1.5 py-0.5 bg-dark-700 text-primary-400 rounded text-sm font-mono">
                {children}
              </code>
            );
          },
          // Tables
          table: ({ children }) => (
            <div className="my-6 overflow-x-auto rounded-lg border border-dark-600">
              <table className="w-full text-sm">
                {children}
              </table>
            </div>
          ),
          thead: ({ children }) => (
            <thead className="bg-dark-700 text-white">
              {children}
            </thead>
          ),
          tbody: ({ children }) => (
            <tbody className="divide-y divide-dark-600">
              {children}
            </tbody>
          ),
          tr: ({ children }) => (
            <tr className="hover:bg-dark-750 transition-colors">
              {children}
            </tr>
          ),
          th: ({ children }) => (
            <th className="px-4 py-3 text-left font-semibold text-white border-b border-dark-600">
              {children}
            </th>
          ),
          td: ({ children }) => (
            <td className="px-4 py-3 text-dark-300">
              {children}
            </td>
          ),
          // Blockquotes
          blockquote: ({ children }) => (
            <blockquote className="my-4 pl-4 border-l-4 border-primary-500 bg-dark-750 py-3 pr-4 rounded-r-lg">
              {children}
            </blockquote>
          ),
          // Horizontal rules
          hr: () => (
            <hr className="my-8 border-dark-600" />
          ),
          // Images - resolve relative paths through API
          img: ({ src, alt }) => (
            <img
              src={resolveImageSrc(src)}
              alt={alt || ''}
              className="my-4 rounded-lg max-w-full h-auto border border-dark-600"
              loading="lazy"
              onError={(e) => {
                // Hide broken images
                (e.target as HTMLImageElement).style.display = 'none';
              }}
            />
          ),
        }}
      >
        {content}
      </ReactMarkdown>
    </article>
  );
};

export default MarkdownRenderer;
