import { useMemo, useState, useRef, useEffect } from 'react';
import { BaseEdge, getBezierPath } from '@xyflow/react';
import { useFlowStoreActions } from '@/stores/flow-store';

const AnimatedMessageEdge = ({
  id,
  source,
  target,
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  data,
  label = '',
  markerEnd,
}: any) => {
  const [edgePath, labelX, labelY] = getBezierPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
  });

  const { deleteEdge, updateEdge } = useFlowStoreActions();
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState(label || '');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (isEditing && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [isEditing]);

  const handleDeleteEdge = (e: React.MouseEvent) => {
    e.stopPropagation();
    deleteEdge(id);
  };

  const handleLabelDoubleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsEditing(true);
    setEditValue(label || '');
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditValue(e.target.value);
  };

  const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSaveLabel();
    } else if (e.key === 'Escape') {
      setIsEditing(false);
      setEditValue(label || '');
    }
  };

  const handleInputBlur = () => {
    handleSaveLabel();
  };

  const handleSaveLabel = () => {
    setIsEditing(false);
    if (editValue !== label) {
      updateEdge({
        id,
        source,
        target,
        sourceHandle: null,
        targetHandle: null,
        type: 'animatedMessage',
        animated: true,
        label: editValue,
        data,
        markerEnd,
      });
    }
  };

  const opacity = data?.opacity ?? 1;

  const messageColor = useMemo(
    () => (collection: string) => {
      switch (collection) {
        case 'event':
          return 'orange';
        case 'command':
          return 'blue';
        case 'query':
          return 'green';
        default:
          return 'gray';
      }
    },
    []
  );

  const randomDelay = useMemo(() => Math.random() * 1, []);

  return (
    // @ts-ignore
    <>
      <BaseEdge id={id} path={edgePath} markerEnd={markerEnd} />
      {/* Circle Icon */}
      <g className={`z-30 ${opacity === 1 ? 'opacity-100' : 'opacity-10'}`}>
        <circle cx="0" cy="0" r="7" fill={messageColor(data?.source)}>
          <animateMotion dur="2s" repeatCount="indefinite" path={edgePath} rotate="auto" begin={`${randomDelay}s`}>
            <mpath href={`#${id}`} />
          </animateMotion>
        </circle>
      </g>
      
      {/* Label background and text */}
      <g>
        {/* Background rectangle */}
        <rect
          x={labelX - (editValue || label || '').length * 3} // Adjust based on text length
          y={labelY - 15} // Position above the text
          width={Math.max((editValue || label || '').length * 6, 40)} // Width based on text length with minimum
          height={20} // Fixed height
          fill="white" // Background color
          opacity={0.8} // Opacity
          rx="4" // Rounded corners
          style={{ cursor: isEditing ? 'text' : 'pointer' }}
          onDoubleClick={handleLabelDoubleClick}
        />

        {/* Input or text element */}
        {isEditing ? (
          <foreignObject
            x={labelX - (editValue || label || '').length * 3}
            y={labelY - 15}
            width={Math.max((editValue || label || '').length * 6, 40)}
            height={20}
          >
            <input
              ref={inputRef}
              type="text"
              value={editValue}
              onChange={handleInputChange}
              onKeyDown={handleInputKeyDown}
              onBlur={handleInputBlur}
              style={{
                width: '100%',
                height: '100%',
                border: 'none',
                outline: 'none',
                background: 'transparent',
                textAlign: 'center',
                fontSize: '10px',
                fontFamily: 'inherit',
              }}
            />
          </foreignObject>
        ) : (
          <text 
            x={labelX} 
            y={labelY} 
            fill="black" 
            fontSize="10" 
            textAnchor="middle" 
            dy="-2"
            style={{ cursor: 'pointer', userSelect: 'none' }}
            onDoubleClick={handleLabelDoubleClick}
          >
            {label || 'Double-click to edit'}
          </text>
        )}
      </g>

      {/* Delete button - always visible */}
      <g>
        {/* Delete button background */}
        <circle
          cx={labelX + (label.length * 3) + 15}
          cy={labelY - 5}
          r="8"
          fill="red"
          opacity={0.9}
          style={{ cursor: 'pointer' }}
          onClick={handleDeleteEdge}
        />
        {/* X icon */}
        <text
          x={labelX + (label.length * 3) + 15}
          y={labelY - 5}
          fill="white"
          fontSize="10"
          textAnchor="middle"
          dy="3"
          style={{ cursor: 'pointer', userSelect: 'none' }}
          onClick={handleDeleteEdge}
        >
          ×
        </text>
      </g>
      {/* Label */}
      {/* <text x={labelX} y={labelY} fill="black" fontSize="12" textAnchor="middle" dy="-5">
        {label}
      </text> */}
    </>
  );
};

export default AnimatedMessageEdge;
