'use client';

import React, { memo } from 'react';
import {
  BaseEdge,
  getSmoothStepPath,
  type EdgeProps,
} from '@xyflow/react';

import { useCanvasState } from '../../hooks/useCanvasState';

export const ConnectionEdge = memo(function ConnectionEdge({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  source,
  target,
  style = {},
  markerEnd,
}: EdgeProps) {
  const selectedNodeId = useCanvasState((s) => s.selectedNodeId);
  const isHighlighted = selectedNodeId === source || selectedNodeId === target;

  const [edgePath] = getSmoothStepPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
    borderRadius: 16,
  });

  return (
    <>
      {/* Glow layer for highlighted state */}
      {isHighlighted && (
        <BaseEdge
          id={`${id}-glow`}
          path={edgePath}
          style={{
            stroke: 'rgba(99, 102, 241, 0.3)',
            strokeWidth: 6,
            filter: 'blur(4px)',
          }}
        />
      )}

      {/* Main edge */}
      <BaseEdge
        id={id}
        path={edgePath}
        markerEnd={markerEnd}
        style={{
          stroke: isHighlighted ? '#6366F1' : '#6B7280',
          strokeWidth: isHighlighted ? 2 : 1.5,
          strokeDasharray: '6 4',
          animation: 'dash-flow 1s linear infinite',
          ...style,
        }}
      />

      {/* CSS animation for dash flow */}
      <style>{`
        @keyframes dash-flow {
          to {
            stroke-dashoffset: -10;
          }
        }
      `}</style>
    </>
  );
});
