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

interface DividerProps {
  color?: string;
  thickness?: string;
  style?: CSSProperties;
}

export const Divider: UserComponent<DividerProps> = ({
  color = '#e4e4e7',
  thickness = '1px',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  return (
    <hr
      ref={(ref: HTMLHRElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        border: 'none',
        borderTop: `${thickness} solid ${color}`,
        margin: '16px 0',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    />
  );
};

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

Divider.craft = {
  displayName: 'Divider',
  props: {
    color: '#e4e4e7',
    thickness: '1px',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
};

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

(Divider as any).toHtml = (props: DividerProps, _childrenHtml: string) => {
  const styleStr = cssPropsToString({
    border: 'none',
    borderTop: `${props.thickness || '1px'} solid ${props.color || '#e4e4e7'}`,
    margin: '16px 0',
    ...props.style,
  });
  return { html: `<hr${styleStr ? ` style="${styleStr}"` : ''} />` };
};
