/**
 * EdgeOrderBadge - Renders the draggable edge order number badge
 * displayed near edges when edge ordering is visible. Supports
 * drag-and-drop reordering of edges from the same source node.
 */
import React from 'react';
import type { EdgeOrderInfo } from '../../types/settings';

interface EdgeOrderBadgeProps {
  edgeId: string;
  edgeOrderInfo: EdgeOrderInfo;
  isLocked: boolean;
  onReorderEdge?: (sourceNodeId: string, fromOrder: number, toOrder: number) => void;
}

const EdgeOrderBadge: React.FC<EdgeOrderBadgeProps> = ({
  edgeId,
  edgeOrderInfo,
  isLocked,
  onReorderEdge,
}) => {
  if (edgeOrderInfo.pathX === undefined || edgeOrderInfo.totalEdges <= 1) {
    return null;
  }

  return (
    <div
      className="edge-order-number nodrag nopan"
      style={{
        transform: `translate(-50%, -50%) translate(${edgeOrderInfo.pathX}px, ${(edgeOrderInfo.pathY ?? 0) - 20}px)`,
      }}
      draggable={!isLocked}
      onMouseDown={(e) => {
        e.stopPropagation();
      }}
      onDragStart={(e) => {
        if (isLocked) return;
        e.stopPropagation();
        e.dataTransfer.setData('edgeOrderReorder', JSON.stringify({
          edgeId: edgeId,
          sourceNodeId: edgeOrderInfo.sourceNodeId || edgeId.split('_to_')[0],
          currentOrder: edgeOrderInfo.order,
          totalEdges: edgeOrderInfo.totalEdges
        }));
        e.dataTransfer.effectAllowed = 'move';

        const dragImage = (e.target as HTMLElement).cloneNode(true) as HTMLElement;
        dragImage.style.position = 'absolute';
        dragImage.style.top = '-1000px';
        document.body.appendChild(dragImage);
        e.dataTransfer.setDragImage(dragImage, 8, 8);
        setTimeout(() => document.body.removeChild(dragImage), 0);

        (e.target as HTMLElement).classList.add('dragging');
      }}
      onDragEnd={(e) => {
        (e.target as HTMLElement).classList.remove('dragging');
      }}
      onDragOver={(e) => {
        if (isLocked) return;
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        (e.currentTarget as HTMLElement).classList.add('drag-over');
      }}
      onDragLeave={(e) => {
        (e.currentTarget as HTMLElement).classList.remove('drag-over');
      }}
      onDrop={(e) => {
        if (isLocked) return;
        e.preventDefault();
        e.stopPropagation();

        (e.currentTarget as HTMLElement).classList.remove('drag-over');

        try {
          const rawData = e.dataTransfer.getData('edgeOrderReorder');
          if (!rawData || rawData.trim() === '') {
            return;
          }

          const dragData = JSON.parse(rawData);
          const targetOrder = edgeOrderInfo.order;
          const sourceNodeId = dragData.sourceNodeId;

          if (dragData.currentOrder !== targetOrder && dragData.sourceNodeId === (edgeOrderInfo.sourceNodeId || edgeId.split('_to_')[0])) {
            if (onReorderEdge) {
              onReorderEdge(sourceNodeId, dragData.currentOrder, targetOrder);
            }
          }
        } catch (error) {
          console.debug('Drop ignored, not edge order data:', error);
        }
      }}
    >
      <div className="edge-order-badge">
        {edgeOrderInfo.order}
      </div>
    </div>
  );
};

export default EdgeOrderBadge;
