"use client";

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

interface MermaidProps {
  graph?: string;
  children?: React.ReactNode;
  id?: string;
  title?: string;
  showShare?: boolean;
  fontSize?: string;
  nodeFontSize?: string;
  labelFontSize?: string;
  actorFontSize?: string;
  messageFontSize?: string;
  noteFontSize?: string;
  titleFontSize?: string;
  sectionFontSize?: string;
  legendFontSize?: string;
}

export const Mermaid: React.FC<MermaidProps> = ({
  graph,
  children,
  id: providedId,
  title,
  showShare = false,
  fontSize = "16px",
  nodeFontSize,
  labelFontSize,
  actorFontSize,
  messageFontSize,
  noteFontSize,
  titleFontSize,
  sectionFontSize,
  legendFontSize,
}) => {
  const [id, setId] = useState<string | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [svgContent, setSvgContent] = useState<string>("");

  // Extract text from React children nodes (MDX parses multi-line content as React nodes)
  const extractTextFromChildren = (node: React.ReactNode): string => {
    if (typeof node === 'string') return node;
    if (typeof node === 'number') return String(node);
    if (Array.isArray(node)) return node.map(extractTextFromChildren).join('\n');
    if (React.isValidElement(node)) {
      const props = node.props as { children?: React.ReactNode };
      if (props.children) {
        return extractTextFromChildren(props.children);
      }
    }
    return '';
  };

  const rawGraph = graph || extractTextFromChildren(children) || "";

  // MDXRemote double-escapes \n in plain string props (e.g., "graph TD\\nA-->B" becomes "graph TD\\\\nA-->B")
  // We need to unescape these back to real newlines for Mermaid to parse
  const sanitizedGraph = rawGraph
    .trim()
    .replace(/^`+|`+$/g, '')
    .replace(/\\n/g, '\n')
    .replace(/\\"/g, '"')
    .replace(/\\'/g, "'");

  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: "base",
      darkMode: false,
      themeVariables: {
        // Base colors - industrial slate/white palette
        primaryColor: "#ffffff",
        primaryTextColor: "#1e293b",
        primaryBorderColor: "#cbd5e1",
        lineColor: "#94a3b8",
        secondaryColor: "#f8fafc",
        tertiaryColor: "#f1f5f9",

        // Background colors
        background: "#ffffff",
        mainBkg: "#ffffff",
        secondBkg: "#f8fafc",
        tertiaryBkg: "#f1f5f9",

        // Text colors
        textColor: "#1e293b",
        labelTextColor: "#475569",

        // Node styling
        nodeBorder: "#cbd5e1",
        clusterBkg: "#f8fafc",
        clusterBorder: "#cbd5e1",

        // Edge/line styling
        edgeLabelBackground: "#ffffff",

        // Font
        fontFamily: "Inter, system-ui, sans-serif",
        fontSize: fontSize,
        nodeFontSize: nodeFontSize || fontSize,
        labelFontSize: labelFontSize || fontSize,
        actorFontSize: actorFontSize || fontSize,
        messageFontSize: messageFontSize || fontSize,
        noteFontSize: noteFontSize || fontSize,
        titleFontSize: titleFontSize || "20px",
        sectionFontSize: sectionFontSize || fontSize,
        legendFontSize: legendFontSize || fontSize,

        // Pie Chart Colors - High Contrast Industrial Palette
        pie1: "#0f172a", // Deep Navy
        pie2: "#334155", // Slate Blue
        pie3: "#64748b", // Steel Gray
        pie4: "#94a3b8", // Muted Steel
        pie5: "#cbd5e1", // Concrete
        pie6: "#1e293b", // Slate 800
        pie7: "#475569", // Slate 600
        pie8: "#000000", // Pure Black for accents
        pie9: "#e2e8f0", // Light Concrete
        pie10: "#020617", // Slate 950
        pie11: "#525252", // Neutral 600
        pie12: "#262626", // Neutral 800
      },
      securityLevel: "loose",
    });

    const render = async () => {
      if (containerRef.current && id) {
        if (!sanitizedGraph || sanitizedGraph.trim() === "") {
          console.warn("Mermaid: Empty or invalid graph provided, skipping render.");
          return;
        }

        try {
          const { svg } = await mermaid.render(`${id}-svg`, sanitizedGraph);
          containerRef.current.innerHTML = svg;
          setSvgContent(svg);
          setIsRendered(true);
        } catch (err) {
          console.error("Mermaid rendering failed:", err);
          console.error("Graph that failed:", sanitizedGraph);
          const errorMessage = err instanceof Error ? err.message : String(err);
          setError(`Failed to render diagram: ${errorMessage}`);
          setIsRendered(true);
        }
      }
    };

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

  if (!id) return null;

  return (
    <div className="mermaid-wrapper not-prose relative left-1/2 right-1/2 -ml-[50vw] -mr-[50vw] w-screen px-5 md:px-16 py-12 bg-slate-50/50 border-y border-slate-100">
      <div className="max-w-7xl mx-auto">
        {title && (
          <h4 className="text-center text-sm font-bold text-slate-700 mb-8 uppercase tracking-[0.2em]">
            {title}
          </h4>
        )}
        <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}
            style={{
              maxWidth: "100%",
              overflow: "visible",
            }}
          >
            {error ? (
              <div className="text-red-500 p-4 border border-red-200 rounded bg-red-50 text-sm">
                {error}
              </div>
            ) : (
              sanitizedGraph
            )}
          </div>
        </div>
        {showShare && id && (
          <div className="flex justify-center mt-8">
            <DiagramShareButton
              diagramId={id}
              title={title}
              svgContent={svgContent}
            />
          </div>
        )}
      </div>
    </div>
  );
};
