"use client";

import React, { useEffect, useRef, useState } from "react";
import mermaid from "mermaid";

interface MermaidProps {
  graph: string;
  id?: string;
}

export const Mermaid: React.FC<MermaidProps> = ({ graph, id: providedId }) => {
  const [id, setId] = useState<string | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setId(
      providedId || `mermaid-${Math.random().toString(36).substring(2, 11)}`,
    );
  }, [providedId]);
  const [isRendered, setIsRendered] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    mermaid.initialize({
      startOnLoad: false,
      theme: "default",
      darkMode: false,
      themeVariables: {
        fontFamily: "Inter, system-ui, sans-serif",
        fontSize: "16px",
        primaryColor: "#ffffff",
        nodeBorder: "#e2e8f0",
        mainBkg: "#ffffff",
        lineColor: "#cbd5e1",
      },
      securityLevel: "loose",
    });

    const render = async () => {
      if (containerRef.current && id) {
        try {
          const { svg } = await mermaid.render(`${id}-svg`, graph);
          containerRef.current.innerHTML = svg;
          setIsRendered(true);
        } catch (err) {
          console.error("Mermaid rendering failed:", err);
          setError("Failed to render diagram. Please check the syntax.");
          setIsRendered(true);
        }
      }
    };

    if (id) {
      render();
    }
  }, [graph, id]);

  if (!id) return null;

  return (
    <div className="mermaid-wrapper my-12 not-prose w-full overflow-hidden">
      <div className="flex justify-center w-full">
        <div
          ref={containerRef}
          className={`mermaid transition-opacity duration-500 w-full flex justify-center ${isRendered ? "opacity-100" : "opacity-0"}`}
          id={id}
        >
          {error ? (
            <div className="text-red-500 p-4 border border-red-200 rounded bg-red-50 text-sm">
              {error}
            </div>
          ) : (
            graph
          )}
        </div>
      </div>
    </div>
  );
};
