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

interface ButtonLinkProps {
  text?: string;
  href?: string;
  target?: '_self' | '_blank';
  style?: CSSProperties;
}

export const ButtonLink: UserComponent<ButtonLinkProps> = ({
  text = 'Click Me',
  href = '#',
  target = '_self',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  return (
    <a
      ref={(ref: HTMLAnchorElement | null) => { if (ref) connect(drag(ref)); }}
      href={href}
      target={target}
      onClick={(e) => {
        // Prevent navigation inside editor
        e.preventDefault();
      }}
      style={{
        display: 'inline-block',
        textDecoration: 'none',
        cursor: 'pointer',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      {text}
    </a>
  );
};

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

ButtonLink.craft = {
  displayName: 'Button',
  props: {
    text: 'Click Me',
    href: '#',
    target: '_self',
    style: {
      backgroundColor: '#3b82f6',
      color: '#ffffff',
      padding: '12px 24px',
      borderRadius: '8px',
      fontWeight: '600',
      fontSize: '16px',
      border: 'none',
    },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
};

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

(ButtonLink as any).toHtml = (props: ButtonLinkProps, _childrenHtml: string) => {
  const styleStr = cssPropsToString({
    display: 'inline-block',
    textDecoration: 'none',
    ...props.style,
  });
  const escapedText = escapeHtml(props.text || '');
  const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
  return {
    html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
  };
};
