"use client";

import React from "react";
import { Mermaid } from "./Mermaid";

interface SequenceParticipant {
  id: string;
  label?: string;
}

interface SequenceMessage {
  from: string;
  to: string;
  message: string;
  type?: "solid" | "dotted" | "async";
}

interface SequenceNote {
  over: string | string[];
  text: string;
}

type SequenceStep = SequenceMessage | SequenceNote;

function isNote(step: SequenceStep): step is SequenceNote {
  return "over" in step;
}

interface DiagramSequenceProps {
  participants: (string | SequenceParticipant)[];
  steps?: SequenceStep[];
  messages?: SequenceMessage[];
  children?: React.ReactNode;
  title?: string;
  caption?: string;
  id?: string;
  showShare?: boolean;
  fontSize?: string;
}

export const DiagramSequence: React.FC<DiagramSequenceProps> = ({
  participants,
  steps,
  messages,
  children,
  title,
  caption,
  id,
  showShare = true,
  fontSize = "16px",
}) => {
  const getArrow = (type?: string) => {
    switch (type) {
      case "dotted":
        return "-->>";
      case "async":
        return "->>";
      default:
        return "->>";
    }
  };

  const participantLines = (participants || []).map((p) => {
    if (typeof p === "string") return `    participant ${p}`;
    return p.label
      ? `    participant ${p.id} as ${p.label}`
      : `    participant ${p.id}`;
  });

  // Support both `steps` (mixed messages + notes) and legacy `messages`
  const allSteps = steps || (messages || []);

  const stepLines = allSteps.map((step) => {
    if (isNote(step)) {
      const over = Array.isArray(step.over) ? step.over.join(",") : step.over;
      return `    Note over ${over}: ${step.text}`;
    }
    return `    ${step.from}${getArrow(step.type)}${step.to}: ${step.message}`;
  });

  const participantLinesSection = participantLines.length > 0 ? `${participantLines.join("\n")}\n` : "";
  const generatedStepsSection = stepLines.length > 0 ? stepLines.join("\n") : "";

  const sequenceGraph = children
    ? (typeof children === "string" ? children : "")
    : `sequenceDiagram\n${participantLinesSection}${generatedStepsSection}`;

  return (
    <div className="my-12">
      <Mermaid
        graph={sequenceGraph}
        id={id}
        title={title}
        showShare={showShare}
        fontSize={fontSize}
      />
      {caption && (
        <div className="text-center text-xs text-slate-400 mt-4 italic">
          {caption}
        </div>
      )}
    </div>
  );
};

