import { memo, useMemo } from 'react';
import { Handle, Position, type NodeProps } from '@xyflow/react';
import { Scale } from 'lucide-react';

export const LBNode = memo(({ data, selected }: NodeProps) => {
  const label = (data as { label?: string }).label ?? 'Load Balancer';
  
  const meta = useMemo(() => {
    try {
      return (data as any).metadata ? JSON.parse((data as any).metadata) : {};
    } catch {
      return {};
    }
  }, [data]);
  
  const hasAddress = meta.ipAddress || meta.port;
  return (
    <div className={`min-w-[140px] bg-slate-800 border rounded-lg shadow-lg overflow-hidden ${selected ? 'ring-2 ring-orange-500 border-orange-500' : 'border-orange-700'}`}>
      <Handle type="target" position={Position.Top} className="!bg-orange-400 !border-orange-600" />
      <div className="px-3 py-2 flex flex-col gap-1">
        <div className="flex items-center gap-2">
          <Scale size={13} className="text-orange-400 shrink-0" />
          <span className="text-xs font-medium text-slate-100 truncate">{label}</span>
        </div>
        {hasAddress && (
          <div className="text-[10px] text-slate-400 font-mono pl-[21px] truncate">
            {meta.ipAddress}
            {meta.ipAddress && meta.port && ':'}
            {meta.port}
          </div>
        )}
      </div>
      <Handle type="source" position={Position.Bottom} className="!bg-orange-400 !border-orange-600" />
    </div>
  );
});
LBNode.displayName = 'LBNode';
