import React, { useEffect, useRef, useState } from "react";
import { GitBranch, Maximize2, Minimize2, Copy, Check } from "lucide-react";

let mermaidInitialized = false;

export default function MermaidDiagram({ code, title }) {
  const containerRef = useRef(null);
  const [svg, setSvg] = useState("");
  const [error, setError] = useState(null);
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    let cancelled = false;

    async function render() {
      try {
        const mermaid = (await import("mermaid")).default;

        if (!mermaidInitialized) {
          mermaid.initialize({
            startOnLoad: false,
            theme: "dark",
            themeVariables: {
              primaryColor: "#e53e3e",
              primaryTextColor: "#fff",
              primaryBorderColor: "#e53e3e",
              lineColor: "#6b6b8a",
              secondaryColor: "#1a1a2e",
              tertiaryColor: "#16162a",
              background: "#0f0f1a",
              mainBkg: "#1a1a2e",
              nodeBorder: "#e53e3e",
              clusterBkg: "#16162a",
              titleColor: "#fff",
              edgeLabelBackground: "#1a1a2e",
            },
            fontFamily: "Inter, system-ui, sans-serif",
            fontSize: 14,
          });
          mermaidInitialized = true;
        }

        const id = `mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`;
        const { svg: renderedSvg } = await mermaid.render(id, code.trim());

        if (!cancelled) {
          setSvg(renderedSvg);
          setError(null);
        }
      } catch (e) {
        if (!cancelled) {
          setError(e.message || "Failed to render diagram");
          setSvg("");
        }
      }
    }

    if (code?.trim()) render();
    return () => { cancelled = true; };
  }, [code]);

  function handleCopy() {
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  if (error) {
    return (
      <div className="rounded-xl border border-red-500/30 bg-red-500/5 p-4">
        <div className="flex items-center gap-2 text-red-400 text-xs mb-2">
          <GitBranch size={14} />
          <span>Diagram Error</span>
        </div>
        <pre className="text-xs text-red-300/70 font-mono">{error}</pre>
        <pre className="text-xs text-anton-muted font-mono mt-2 bg-anton-bg p-2 rounded">{code}</pre>
      </div>
    );
  }

  if (!svg) {
    return (
      <div className="rounded-xl border border-anton-border bg-anton-card p-8 flex items-center justify-center">
        <div className="flex items-center gap-2 text-anton-muted text-sm">
          <div className="w-4 h-4 border-2 border-anton-accent border-t-transparent rounded-full animate-spin" />
          Rendering diagram...
        </div>
      </div>
    );
  }

  return (
    <div className={`rounded-xl border border-anton-border overflow-hidden bg-anton-card ${expanded ? "fixed inset-4 z-50" : ""}`}>
      <div className="flex items-center justify-between px-3 py-2 bg-anton-surface border-b border-anton-border">
        <div className="flex items-center gap-2">
          <GitBranch size={14} className="text-purple-400" />
          <span className="text-xs font-medium text-white">{title || "Diagram"}</span>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={handleCopy} className="p-1.5 rounded text-anton-muted hover:text-white transition">
            {copied ? <Check size={14} className="text-green-400" /> : <Copy size={14} />}
          </button>
          <button onClick={() => setExpanded(!expanded)} className="p-1.5 rounded text-anton-muted hover:text-white transition">
            {expanded ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
          </button>
        </div>
      </div>
      <div
        ref={containerRef}
        className="p-6 flex justify-center overflow-auto bg-[#0f0f1a]"
        style={{ minHeight: expanded ? "calc(100vh - 100px)" : "200px" }}
        dangerouslySetInnerHTML={{ __html: svg }}
      />
    </div>
  );
}