import { Handle, Position } from "@xyflow/react";
import type { NodeProps } from "@xyflow/react";

import type { DiagramNode } from "../graph";

function GatewayMarker({ type }: { type: string }) {
  const bare = type.startsWith("bpmn:") ? type.slice(5) : type;

  if (bare === "gateway-exclusive") {
    return (
      <g>
        <line
          x1={17}
          y1={17}
          x2={33}
          y2={33}
          style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 3 }}
        />
        <line
          x1={33}
          y1={17}
          x2={17}
          y2={33}
          style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 3 }}
        />
      </g>
    );
  }
  if (bare === "gateway-parallel") {
    return (
      <g>
        <line
          x1={25}
          y1={16}
          x2={25}
          y2={34}
          style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 3 }}
        />
        <line
          x1={16}
          y1={25}
          x2={34}
          y2={25}
          style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 3 }}
        />
      </g>
    );
  }
  // gateway-inclusive
  return (
    <circle
      cx={25}
      cy={25}
      r={9}
      fill="none"
      style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 2.5 }}
    />
  );
}

export function BpmnGatewayNode({ data }: NodeProps) {
  const d = data as unknown as DiagramNode & { label: string };

  return (
    <div className="bpmn-gateway-node">
      <svg width={50} height={50} viewBox="0 0 50 50">
        <polygon
          points="25,1 49,25 25,49 1,25"
          fill="var(--node-bg)"
          style={{ stroke: "var(--bpmn-gateway)", strokeWidth: 2 }}
        />
        <GatewayMarker type={d.type} />
      </svg>
      {d.label && <div className="bpmn-event-label">{d.label}</div>}
      <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
      <Handle
        type="target"
        position={Position.Left}
        id="left"
        style={{ opacity: 0 }}
      />
      <Handle
        type="source"
        position={Position.Bottom}
        style={{ opacity: 0 }}
      />
      <Handle
        type="source"
        position={Position.Right}
        id="right"
        style={{ opacity: 0 }}
      />
    </div>
  );
}
