
import React, { useEffect, useRef, useState } from 'react';
import mermaid from 'mermaid';
import { AlertTriangle } from 'lucide-react';

interface Props {
  chart: string;
  theme?: 'light' | 'dark';
}

const MermaidDiagram: React.FC<Props> = ({ chart, theme = 'light' }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [svg, setSvg] = useState<string>('');
  const [error, setError] = useState<string>('');

  useEffect(() => {
    mermaid.initialize({
      startOnLoad: false,
      theme: theme === 'dark' ? 'dark' : 'default',
      securityLevel: 'loose',
      fontFamily: 'Inter, sans-serif',
    });
  }, [theme]);

  useEffect(() => {
    const renderChart = async () => {
      if (!containerRef.current) return;
      
      setError('');
      
      try {
        // Clean up the chart string - remove any markdown code fences
        let cleanChart = chart.trim();
        if (cleanChart.startsWith('```')) {
          cleanChart = cleanChart.replace(/^```(?:mermaid)?\n?/, '').replace(/\n?```$/, '');
        }
        
        const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
        // Mermaid render returns an object with svg property in newer versions
        const { svg } = await mermaid.render(id, cleanChart);
        setSvg(svg);
      } catch (err: any) {
        console.error('Mermaid failed to render:', err);
        setError(err.message || 'Failed to render diagram');
        setSvg('');
      }
    };

    if (chart) {
      renderChart();
    }
  }, [chart, theme]);

  if (error) {
    return (
      <div className="w-full p-6 rounded-xl bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800">
        <div className="flex items-start gap-3">
          <AlertTriangle size={20} className="text-amber-500 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-semibold text-amber-700 dark:text-amber-300 text-sm">
              Diagram could not be rendered
            </p>
            <p className="mt-1 text-xs text-amber-600 dark:text-amber-400 font-mono">
              {error}
            </p>
            <details className="mt-3">
              <summary className="text-xs text-amber-600 dark:text-amber-400 cursor-pointer hover:underline">
                Show raw diagram code
              </summary>
              <pre className="mt-2 p-3 bg-white dark:bg-gray-900 rounded-lg text-xs overflow-auto max-h-40 border border-amber-100 dark:border-amber-900">
                {chart}
              </pre>
            </details>
          </div>
        </div>
      </div>
    );
  }

  if (!svg) {
    return (
      <div className="w-full h-40 flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-gray-300 border-t-brand-500 rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div 
      className="w-full h-full flex items-center justify-center p-4 mermaid-container overflow-hidden [&_svg]:max-w-full [&_svg]:h-auto"
      ref={containerRef}
      dangerouslySetInnerHTML={{ __html: svg }}
    />
  );
};

export default MermaidDiagram;
