import {
  BaseEdge,
  EdgeLabelRenderer,
  getSmoothStepPath,
  Position,
} from "@xyflow/react";
import type { EdgeProps } from "@xyflow/react";

/** Offset (px) from the endpoint along the edge segment for cardinality labels. */
const CARD_OFFSET = 24;

/** Compute cardinality label position offset along the actual edge segment direction. */
function cardinalityOffset(
  x: number,
  y: number,
  position: Position,
): { x: number; y: number } {
  switch (position) {
    case Position.Top:
      return { x, y: y - CARD_OFFSET };
    case Position.Bottom:
      return { x, y: y + CARD_OFFSET };
    case Position.Left:
      return { x: x - CARD_OFFSET, y };
    case Position.Right:
      return { x: x + CARD_OFFSET, y };
  }
}

export function ErRelationshipEdge(props: EdgeProps) {
  const [edgePath, labelX, labelY] = getSmoothStepPath({
    sourceX: props.sourceX,
    sourceY: props.sourceY,
    targetX: props.targetX,
    targetY: props.targetY,
    sourcePosition: props.sourcePosition,
    targetPosition: props.targetPosition,
  });

  const cardinality = (
    props.data as Record<string, unknown> | undefined
  )?.cardinality as string | undefined;

  const parts = cardinality?.split(":") ?? [];
  const srcCard = parts[0] || undefined;
  const tgtCard = parts[1] || undefined;

  const srcPos = cardinalityOffset(
    props.sourceX,
    props.sourceY,
    props.sourcePosition,
  );
  const tgtPos = cardinalityOffset(
    props.targetX,
    props.targetY,
    props.targetPosition,
  );

  return (
    <>
      <BaseEdge
        id={props.id}
        path={edgePath}
        markerEnd="url(#er-arrow)"
        style={{ stroke: "var(--diagram-er)", strokeWidth: 1.5 }}
        label={props.label}
        labelStyle={{ fill: "var(--foreground)", fontSize: 11 }}
        labelBgStyle={{
          fill: "var(--node-bg)",
          fillOpacity: 0.9,
        }}
        labelShowBg
      />
      <EdgeLabelRenderer>
        {srcCard && (
          <div
            className="er-cardinality nodrag nopan"
            style={{
              position: "absolute",
              transform: `translate(-50%, -50%) translate(${srcPos.x}px, ${srcPos.y}px)`,
              pointerEvents: "none",
            }}
          >
            {srcCard}
          </div>
        )}
        {tgtCard && (
          <div
            className="er-cardinality nodrag nopan"
            style={{
              position: "absolute",
              transform: `translate(-50%, -50%) translate(${tgtPos.x}px, ${tgtPos.y}px)`,
              pointerEvents: "none",
            }}
          >
            {tgtCard}
          </div>
        )}
      </EdgeLabelRenderer>
    </>
  );
}
