import React, { useEffect, useRef } from 'react';
import mermaid from 'mermaid';

interface MermaidDiagramProps {
  chart: string;
  className?: string;
}

const MermaidDiagram: React.FC<MermaidDiagramProps> = ({ chart, className = '' }) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    mermaid.initialize({ 
      startOnLoad: true,
      theme: 'base',
      themeVariables: {
        primaryColor: '#3b82f6',
        primaryTextColor: '#1f2937',
        primaryBorderColor: '#6b7280',
        lineColor: '#6b7280',
        secondaryColor: '#e5e7eb',
        tertiaryColor: '#f9fafb',
        background: '#ffffff',
        mainBkg: '#ffffff',
        secondBkg: '#f9fafb',
        tertiaryBkg: '#f3f4f6',
        nodeBkg: '#f8fafc',
        clusterBkg: '#f1f5f9',
        edgeLabelBackground: '#ffffff'
      },
      flowchart: {
        nodeSpacing: 20,
        rankSpacing: 20,
        curve: 'basis',
        padding: 10
      },
      fontFamily: 'ui-sans-serif, system-ui, sans-serif',
      fontSize: '12px'
    });
  }, []);

  useEffect(() => {
    if (ref.current && chart) {
      ref.current.innerHTML = '';
      const uniqueId = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
      
      try {
        mermaid.render(uniqueId, chart).then(({ svg }) => {
          if (ref.current) {
            // Clean up the SVG to ensure proper scaling
            const cleanedSvg = svg.replace(/width="[^"]*"/, '').replace(/height="[^"]*"/, '');
            ref.current.innerHTML = cleanedSvg;
            
            // Ensure SVG fits container
            const svgElement = ref.current.querySelector('svg');
            if (svgElement) {
              svgElement.setAttribute('width', '100%');
              svgElement.setAttribute('height', '100%');
              svgElement.style.maxWidth = '100%';
              svgElement.style.maxHeight = '100%';
            }
          }
        }).catch((error) => {
          console.error('Mermaid rendering error:', error);
          if (ref.current) {
            ref.current.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400 text-xs">Preview unavailable</div>';
          }
        });
      } catch (error) {
        console.error('Mermaid parsing error:', error);
        if (ref.current) {
          ref.current.innerHTML = '<div class="flex items-center justify-center h-full text-gray-400 text-xs">Preview unavailable</div>';
        }
      }
    }
  }, [chart]);

  return <div ref={ref} className={`mermaid-container ${className}`} />;
};

export default MermaidDiagram;