import React, { useEffect, useState } from 'react';
import { Box, Button, Typography, CircularProgress } from '@mui/material';

interface MermaidDiagramProps {
    src: string;
    title?: string;
}

declare global {
    interface Window {
        mermaid: any;
    }
}

const MermaidDiagram = ({ src, title = 'Structure Preview' }: MermaidDiagramProps) => {
    const [renderedSvg, setRenderedSvg] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);
    const [showDiagram, setShowDiagram] = useState(false);

    useEffect(() => {
        if (!showDiagram || !src) return;

        const fetchAndRender = async () => {
            setLoading(true);
            try {
                const res = await fetch(src);
                const raw = await res.text();
                const { svg } = await window.mermaid.render(
                    'mmd-diagram-' + Math.random().toString(36).substring(2),
                    raw
                );
                setRenderedSvg(svg);
            } catch (err) {
                setRenderedSvg(`<p style="color:var(--red);">Failed to render diagram.</p>`);
            } finally {
                setLoading(false);
            }
        };

        fetchAndRender();
    }, [src, showDiagram]);

    return (
        <Box className="flowchart-container">
            <Box className="flowchart-header">
                <Typography variant="h6">{title}</Typography>
                <Button
                    variant="contained"
                    color="success"
                    sx={{ color: 'white' }}
                    onClick={() => {
                        setRenderedSvg(null); // Optional reset
                        setShowDiagram(prev => !prev);
                    }}
                >
                    {showDiagram ? 'Hide Diagram' : 'Show Diagram'}
                </Button>
            </Box>

            {showDiagram && (
                <Box className="flowchart-svg-container">
                    {loading && (
                        <Box className="flowchart-spinner">
                            <CircularProgress color="success" />
                        </Box>
                    )}
                    <Box
                        className="flowchart-svg"
                        role="img"
                        aria-label={title}
                        dangerouslySetInnerHTML={{ __html: renderedSvg || '' }}
                    />
                </Box>
            )}
        </Box>
    );
};

export default MermaidDiagram;
