import { EdgeLabelRenderer } from "@xyflow/react";
import type { EdgeProps } from "@xyflow/react";
import { SEQ_LAYOUT, SEQ_SIZES } from "./constants";

const SELF_MSG_WIDTH = 40;

export function SeqReturnEdge(props: EdgeProps) {
  const edgeData = props.data as Record<string, unknown> | undefined;
  const order = (edgeData?.order as number) ?? 0;
  const messageY = (edgeData?.messageY as number) ??
    SEQ_LAYOUT.messageStartY + order * SEQ_LAYOUT.messageSpacing;

  const isSelfMessage = props.source === props.target;

  if (isSelfMessage) {
    const x = props.sourceX + SEQ_SIZES.participant.w / 2;
    const loopRight = x + SELF_MSG_WIDTH;
    const loopBottom = messageY + SEQ_LAYOUT.messageSpacing * 0.6;
    const path = `M ${x} ${messageY} L ${loopRight} ${messageY} L ${loopRight} ${loopBottom} L ${x} ${loopBottom}`;

    return (
      <>
        <path
          d={path}
          stroke="var(--diagram-sequence)"
          strokeWidth={1}
          strokeDasharray="4 4"
          fill="none"
          markerEnd="url(#seq-arrow-filled)"
        />
        {props.label && (
          <EdgeLabelRenderer>
            <div
              className="seq-edge-label seq-edge-label-positioned"
              style={{
                transform: `translate(0, -100%) translate(${loopRight + 4}px, ${messageY + (loopBottom - messageY) / 2}px)`,
              }}
            >
              {props.label}
            </div>
          </EdgeLabelRenderer>
        )}
      </>
    );
  }

  const isLeftToRight = props.sourceX < props.targetX;
  const startX = isLeftToRight
    ? props.sourceX + SEQ_SIZES.participant.w / 2
    : props.sourceX - SEQ_SIZES.participant.w / 2;
  const endX = isLeftToRight
    ? props.targetX - SEQ_SIZES.participant.w / 2
    : props.targetX + SEQ_SIZES.participant.w / 2;

  const path = `M ${startX} ${messageY} L ${endX} ${messageY}`;

  return (
    <>
      <path
        d={path}
        stroke="var(--diagram-sequence)"
        strokeWidth={1}
        strokeDasharray="4 4"
        fill="none"
        markerEnd="url(#seq-arrow-filled)"
      />
      {props.label && (
        <EdgeLabelRenderer>
          <div
            className="seq-edge-label seq-edge-label-positioned"
            style={{
              transform: `translate(-50%, -100%) translate(${(startX + endX) / 2}px, ${messageY - 4}px)`,
            }}
          >
            {props.label}
          </div>
        </EdgeLabelRenderer>
      )}
    </>
  );
}
