import React, { memo } from 'react';
import { Handle, Position, type NodeProps } from '@xyflow/react';

const CATEGORY_COLORS: Record<string, { bg: string; border: string }> = {
  TRIGGER: { bg: '#e6f7ff', border: '#91caff' },
  ACTION: { bg: '#f6ffed', border: '#b7eb8f' },
  CONDITION: { bg: '#fff7e6', border: '#ffd591' },
  LOOP: { bg: '#f9f0ff', border: '#d3adf7' },
  APPROVAL: { bg: '#fff1f0', border: '#ffa39e' },
  SUB_WORKFLOW: { bg: '#f0f5ff', border: '#adc6ff' },
};

export interface CustomNodeData {
  label: string;
  category: string;
  isSelected: boolean;
  readonly?: boolean;
  [key: string]: unknown;
}

export const CustomNode = memo(({ data }: NodeProps) => {
  const nodeData = data as CustomNodeData;
  const colors = CATEGORY_COLORS[nodeData.category] || CATEGORY_COLORS.ACTION;

  return (
    <div
      style={{
        background: colors.bg,
        border: nodeData.isSelected
          ? '2px solid #1677ff'
          : `1px solid ${colors.border}`,
        borderRadius: 8,
        padding: '8px 16px',
        fontSize: 14,
        minWidth: 120,
        textAlign: 'center',
        boxShadow: nodeData.isSelected
          ? '0 0 0 2px rgba(22,119,255,0.2)'
          : undefined,
      }}
    >
      {!nodeData.readonly && (
        <Handle
          type="target"
          position={Position.Top}
          style={{
            width: 14,
            height: 14,
            background: '#fff',
            border: '2px solid #555',
            cursor: 'crosshair',
          }}
        />
      )}
      {nodeData.readonly && (
        <Handle
          type="target"
          position={Position.Top}
          style={{
            width: 0,
            height: 0,
            border: 'none',
            background: 'transparent',
            visibility: 'hidden',
          }}
        />
      )}
      <div>{nodeData.label}</div>
      {!nodeData.readonly && (
        <Handle
          type="source"
          position={Position.Bottom}
          style={{
            width: 14,
            height: 14,
            background: '#fff',
            border: '2px solid #555',
            cursor: 'crosshair',
          }}
        />
      )}
      {nodeData.readonly && (
        <Handle
          type="source"
          position={Position.Bottom}
          style={{
            width: 0,
            height: 0,
            border: 'none',
            background: 'transparent',
            visibility: 'hidden',
          }}
        />
      )}
    </div>
  );
});

CustomNode.displayName = 'CustomNode';
