/**
 * ConditionEdge - Custom ReactFlow edge component for rendering condition edges.
 * Supports draggable control points, condition labels, annotations,
 * replay highlighting, and edge order badges.
 */
import React, { useMemo } from 'react';
import { EdgeLabelRenderer, EdgeProps } from 'reactflow';
import { FiTrash2 } from 'react-icons/fi';
import { useEdgePath } from '../../hooks/useEdgePath';
import { useControlPointDrag } from '../../hooks/useControlPointDrag';
import EdgeOrderBadge from './EdgeOrderBadge';
import { t } from '../../utils/translation';
import { getComponentLabel } from '../../utils/componentUtils';
import Annotation from "../Annotation";
import type { BaseEdgeData } from '../../types/settings';

interface ConditionEdgeData extends BaseEdgeData {
  condition?: string;
  annotation?: string;
  isAnnotationVisible?: boolean;
  onDeleteCondition?: (id: string) => void;
  onToggleAnnotation?: () => void;
}

interface ConditionEdgeProps extends EdgeProps {
  data?: ConditionEdgeData;
}

const ConditionEdge: React.FC<ConditionEdgeProps> = ({
  id,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  data,
  style,
  markerEnd,
  label,
  selected,
}) => {
  // Get selected state from either prop or data
  const isEdgeSelected = selected || data?.isSelected || false;

  // Get control point offset from data
  const controlOffset = useMemo(() => data?.controlOffset || { x: 0, y: 0 }, [data?.controlOffset]);

  // Calculate edge center
  const edgeCenterX = (sourceX + targetX) / 2;
  const edgeCenterY = (sourceY + targetY) / 2;

  const controlPointX = edgeCenterX + controlOffset.x;
  const controlPointY = edgeCenterY + controlOffset.y;

  // Use extracted path calculation hook
  const [edgePath, labelX, labelY] = useEdgePath({
    sourceX,
    sourceY,
    targetX,
    targetY,
    sourcePosition,
    targetPosition,
    controlOffset,
  });

  const hasCondition = data?.condition;
  const hasAnnotation = data?.annotation;
  const isLocked = data?.isLocked || data?.locked;
  const replayHighlight = data?.replayHighlight;

  // Use extracted control point drag hook
  const { isDragging, handleControlPointDrag } = useControlPointDrag({
    id,
    edgeCenterX,
    edgeCenterY,
    isLocked: !!isLocked,
    hasCondition: !!hasCondition,
    label,
    controlOffset,
    onEdgeUpdate: data?.onEdgeUpdate,
  });

  const handleDeleteCondition = (event: React.MouseEvent) => {
    event.stopPropagation();
    if (data?.onDeleteCondition) {
      data.onDeleteCondition(id);
    }
  };

  // Apply locked styling or replay highlight
  const edgeStyle = isLocked ? {
    ...style,
    stroke: 'var(--modeler-color-edge-locked)',
    opacity: 0.6,
    strokeWidth: 1
  } : replayHighlight ? {
    ...style,
    stroke: `${replayHighlight} !important`,
    strokeWidth: 3
  } : style;

  return (
    <>
      {replayHighlight ? (
        <g style={{ stroke: replayHighlight, strokeWidth: 3 }}>
          <path
            id={id}
            style={{ fill: 'none' }}
            className={`react-flow__edge-path ${isLocked ? 'edge-locked' : ''} replay-highlighted`}
            d={edgePath}
            markerEnd={markerEnd}
            stroke={replayHighlight}
            strokeWidth={3}
          />
        </g>
      ) : (
        <>
          <path
            id={id}
            style={edgeStyle}
            className={`react-flow__edge-path ${isLocked ? 'edge-locked' : ''} ${selected ? 'selected' : ''}`}
            d={edgePath}
            markerEnd={markerEnd}
          />
          {/* Show line from center to control point for visual feedback */}
          {isEdgeSelected && (controlOffset.x !== 0 || controlOffset.y !== 0) && (
            <line
              className="edge-guide-line"
              x1={edgeCenterX}
              y1={edgeCenterY}
              x2={controlPointX}
              y2={controlPointY}
            />
          )}
        </>
      )}
      {/* Render control point and labels in EdgeLabelRenderer for proper z-index */}
      {(hasCondition || hasAnnotation || isEdgeSelected || (data?.edgeOrdersVisible && data?.edgeOrderInfo)) && (
        <EdgeLabelRenderer>
          <div
            className="edge-label-container nodrag nopan"
            style={{
              transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
            }}
          >
            {/* Condition Label */}
            {hasCondition && label && (
              <div
                className={`condition-edge-label ${isLocked ? 'condition-edge-label-locked' : ''} ${isEdgeSelected ? 'selected' : ''}`}
              >
                <span>{label}</span>
                {!isLocked && (
                  <button
                    onClick={handleDeleteCondition}
                    className="condition-delete-btn"
                    title={t('Remove @type', { '@type': getComponentLabel('link').toLowerCase() })}
                    aria-label={t('Remove @type', { '@type': getComponentLabel('link').toLowerCase() })}
                  >
                    <FiTrash2 size={12} />
                  </button>
                )}
              </div>
            )}

            {data?.annotation && (
              <Annotation
                annotation={data.annotation}
                isVisible={data?.isAnnotationVisible}
                onToggle={data?.onToggleAnnotation}
                offset={!!(hasCondition && label)}
              />
            )}
          </div>

          {/* Draggable control point when edge is selected */}
          {isEdgeSelected && (
            <div
              className={`edge-control-point-wrapper ${isDragging ? 'dragging' : ''}`}
              onMouseDown={handleControlPointDrag}
              style={{
                transform: `translate(-50%, -50%) translate(${controlPointX}px,${hasCondition && label && (controlOffset.x === 0 && controlOffset.y === 0) ? controlPointY - 25 : controlPointY}px)`,
                cursor: isDragging ? 'grabbing' : 'grab',
              }}
            >
              <svg width="24" height="24">
                <circle className="control-point-outer" cx={12} cy={12} r={12} />
                <circle className="control-point-inner" cx={12} cy={12} r={6} />
              </svg>
            </div>
          )}

          {/* Edge Order Number Badge — visible even in read-only/locked mode,
              but drag-reorder is disabled when any lock is active. */}
          {data?.edgeOrdersVisible && data?.edgeOrderInfo && (
            <EdgeOrderBadge
              edgeId={id}
              edgeOrderInfo={data.edgeOrderInfo}
              isLocked={!!isLocked || !!data?.globalLocked}
              onReorderEdge={data.onReorderEdge}
            />
          )}
        </EdgeLabelRenderer>
      )}
    </>
  );
};

export default ConditionEdge;
