import React, { memo, useRef, useEffect, useState } from 'react';
import { Handle, Position, NodeProps } from 'reactflow';
import { FiLock } from 'react-icons/fi';
import { getComponentLabel } from '../../utils/componentUtils';
import NodeWrapper from './NodeWrapper';
import type { BaseNodeData } from '../../types/settings';

const GatewayNode = memo<NodeProps<BaseNodeData>>(({ data, selected }) => {
  const [diamondSize, setDiamondSize] = useState(56);
  const labelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const measureAndResize = () => {
      if (labelRef.current) {
        // Force a reflow to ensure accurate measurements
        labelRef.current.style.width = 'auto';
        labelRef.current.style.height = 'auto';

        // Measure the label's natural size
        const labelWidth = labelRef.current.scrollWidth;
        const labelHeight = labelRef.current.scrollHeight;

        // Calculate the size needed for the diamond (account for rotation)
        // When rotated 45 degrees, we need sqrt(2) times the content size
        const neededSize = Math.max(56, Math.min(120, Math.max(labelWidth, labelHeight) * 1.5 + 24));

        // Only update if size actually changed to prevent infinite loops
        setDiamondSize(prev => {
          if (Math.abs(prev - neededSize) > 1) {
            return neededSize;
          }
          return prev;
        });
      }
    };

    // Measure immediately
    measureAndResize();

    // Also measure after a short delay to ensure DOM is fully rendered
    const timeoutId = setTimeout(measureAndResize, 10);

    return () => clearTimeout(timeoutId);
  }, [data.label]);

  return (
    <NodeWrapper data={data} selected={selected} nodeClass="gateway-node">
      <Handle
        type="target"
        position={Position.Top}
        className="node-handle"
        id="input"
      />

      <div className="gateway-diamond" style={{ width: diamondSize, height: diamondSize }}>
        <div className="node-body">
          {data.locked && <FiLock className="lock-icon-rotated" />}
          <div className="node-label" ref={labelRef}>{data.label || getComponentLabel('gateway')}</div>
        </div>
      </div>

      <Handle
        type="source"
        position={Position.Right}
        className="node-handle"
        id="true"
        style={{ top: '50%' }}
      />

      <Handle
        type="source"
        position={Position.Bottom}
        className="node-handle"
        id="false"
      />
    </NodeWrapper>
  );
});

GatewayNode.displayName = 'GatewayNode';

export default GatewayNode;
