import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';

interface SpacerProps {
  height?: string;
  style?: CSSProperties;
}

export const Spacer: UserComponent<SpacerProps> = ({
  height = '40px',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  return (
    <div
      ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        height,
        outline: selected ? '2px dashed #3b82f6' : 'none',
        ...style,
        ...(selected && !style.backgroundColor && !style.background
          ? { background: 'rgba(59,130,246,0.05)' }
          : {}),
      }}
    />
  );
};

/* ---------- Craft config ---------- */

Spacer.craft = {
  displayName: 'Spacer',
  props: {
    height: '40px',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
};

/* ---------- HTML export ---------- */

(Spacer as any).toHtml = (props: SpacerProps, _childrenHtml: string) => {
  const styleStr = cssPropsToString({
    height: props.height || '40px',
    ...props.style,
  });
  return { html: `<div${styleStr ? ` style="${styleStr}"` : ''}></div>` };
};
