'use client'

import {
  BaseEdge,
  EdgeLabelRenderer,
  EdgeProps,
  getSmoothStepPath,
} from 'reactflow'
import type { Condition } from '@/types/flowchart'

type ConditionalEdgeData = {
  condition?: Condition
}

export default function ConditionalEdge({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  data,
  markerEnd,
  selected,
}: EdgeProps<ConditionalEdgeData>) {
  const [edgePath, labelX, labelY] = getSmoothStepPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
  })

  const hasCondition = !!data?.condition

  // Format condition as readable label
  const conditionLabel = hasCondition
    ? `${data.condition!.variableName} ${data.condition!.operator} ${data.condition!.value}`
    : null

  return (
    <>
      <BaseEdge
        id={id}
        path={edgePath}
        markerEnd={markerEnd}
        style={{
          strokeDasharray: hasCondition ? '5 5' : undefined,
          stroke: selected ? '#3b82f6' : hasCondition ? '#f59e0b' : '#64748b',
          strokeWidth: selected ? 2 : 1.5,
        }}
      />
      {conditionLabel && (
        <EdgeLabelRenderer>
          <div
            style={{
              position: 'absolute',
              transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
              pointerEvents: 'all',
            }}
            className="rounded border border-amber-300 bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 dark:border-amber-600 dark:bg-amber-900 dark:text-amber-200"
          >
            {conditionLabel}
          </div>
        </EdgeLabelRenderer>
      )}
    </>
  )
}
