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

interface SubscribeFormProps {
  heading?: string;
  placeholder?: string;
  buttonText?: string;
  buttonColor?: string;
  layout?: 'inline' | 'stacked';
  style?: CSSProperties;
}

export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
  heading = 'Subscribe to our newsletter',
  placeholder = 'Enter your email',
  buttonText = 'Subscribe',
  buttonColor = '#3b82f6',
  layout = 'inline',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  const isInline = layout === 'inline';

  return (
    <div
      ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        padding: '40px 24px',
        textAlign: 'center',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      {heading && (
        <h3 style={{
          fontSize: '22px',
          fontWeight: '600',
          color: '#1f2937',
          marginBottom: '20px',
          fontFamily: 'Inter, sans-serif',
        }}>
          {heading}
        </h3>
      )}
      <form
        onSubmit={(e) => e.preventDefault()}
        style={{
          display: 'flex',
          flexDirection: isInline ? 'row' : 'column',
          gap: isInline ? '0' : '12px',
          maxWidth: isInline ? '480px' : '360px',
          margin: '0 auto',
          alignItems: 'stretch',
        }}
      >
        <input
          type="email"
          placeholder={placeholder}
          style={{
            flex: 1,
            padding: '12px 16px',
            fontSize: '15px',
            fontFamily: 'Inter, sans-serif',
            border: '1px solid #d1d5db',
            borderRadius: isInline ? '8px 0 0 8px' : '8px',
            backgroundColor: '#ffffff',
            color: '#1f2937',
            outline: 'none',
            boxSizing: 'border-box',
          }}
        />
        <button
          type="submit"
          style={{
            padding: '12px 24px',
            fontSize: '15px',
            fontWeight: '600',
            fontFamily: 'Inter, sans-serif',
            color: '#ffffff',
            backgroundColor: buttonColor,
            border: 'none',
            borderRadius: isInline ? '0 8px 8px 0' : '8px',
            cursor: 'pointer',
            whiteSpace: 'nowrap',
          }}
        >
          {buttonText}
        </button>
      </form>
    </div>
  );
};

/* ---------- Settings panel ---------- */

const SubscribeFormSettings: React.FC = () => {
  const { actions: { setProp }, props } = useNode((node) => ({
    props: node.data.props as SubscribeFormProps,
  }));

  const labelStyle: CSSProperties = { fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 };
  const inputStyle: CSSProperties = {
    width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7',
    border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12,
  };

  const buttonColorPresets = ['#3b82f6', '#10b981', '#ef4444', '#8b5cf6', '#f59e0b', '#18181b', '#0ea5e9', '#ec4899'];
  const bgPresets = ['#ffffff', '#f8fafc', '#f1f5f9', '#18181b', '#0f172a', '#eff6ff', '#f0fdf4', '#fef3c7'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Heading */}
      <div>
        <label style={labelStyle}>Heading</label>
        <input
          type="text"
          value={props.heading || ''}
          onChange={(e) => setProp((p: SubscribeFormProps) => { p.heading = e.target.value; })}
          placeholder="Subscribe to our newsletter"
          style={inputStyle}
        />
      </div>

      {/* Placeholder */}
      <div>
        <label style={labelStyle}>Placeholder</label>
        <input
          type="text"
          value={props.placeholder || ''}
          onChange={(e) => setProp((p: SubscribeFormProps) => { p.placeholder = e.target.value; })}
          placeholder="Enter your email"
          style={inputStyle}
        />
      </div>

      {/* Button Text */}
      <div>
        <label style={labelStyle}>Button Text</label>
        <input
          type="text"
          value={props.buttonText || ''}
          onChange={(e) => setProp((p: SubscribeFormProps) => { p.buttonText = e.target.value; })}
          placeholder="Subscribe"
          style={inputStyle}
        />
      </div>

      {/* Layout */}
      <div>
        <label style={labelStyle}>Layout</label>
        <div style={{ display: 'flex', gap: 4 }}>
          <button
            onClick={() => setProp((p: SubscribeFormProps) => { p.layout = 'inline'; })}
            style={{
              flex: 1, padding: '6px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
              border: '1px solid #3f3f46',
              background: (props.layout || 'inline') === 'inline' ? '#3b82f6' : '#27272a',
              color: (props.layout || 'inline') === 'inline' ? '#fff' : '#a1a1aa',
              fontWeight: 500,
            }}
          >
            Inline
          </button>
          <button
            onClick={() => setProp((p: SubscribeFormProps) => { p.layout = 'stacked'; })}
            style={{
              flex: 1, padding: '6px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
              border: '1px solid #3f3f46',
              background: props.layout === 'stacked' ? '#3b82f6' : '#27272a',
              color: props.layout === 'stacked' ? '#fff' : '#a1a1aa',
              fontWeight: 500,
            }}
          >
            Stacked
          </button>
        </div>
      </div>

      {/* Button Color */}
      <div>
        <label style={labelStyle}>Button Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {buttonColorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: SubscribeFormProps) => { p.buttonColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: (props.buttonColor || '#3b82f6') === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Background */}
      <div>
        <label style={labelStyle}>Background</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {bgPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: SubscribeFormProps) => { p.style = { ...p.style, backgroundColor: c }; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.style?.backgroundColor === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

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

SubscribeForm.craft = {
  displayName: 'Subscribe Form',
  props: {
    heading: 'Subscribe to our newsletter',
    placeholder: 'Enter your email',
    buttonText: 'Subscribe',
    buttonColor: '#3b82f6',
    layout: 'inline',
    style: { backgroundColor: '#f8fafc' },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: SubscribeFormSettings,
  },
};

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

(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string) => {
  const esc = (s: any) => String(s ?? "").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  const {
    heading = 'Subscribe to our newsletter',
    placeholder = 'Enter your email',
    buttonText = 'Subscribe',
    buttonColor = '#3b82f6',
    layout = 'inline',
    style = {},
  } = props;

  const isInline = layout === 'inline';

  const wrapperStyle = cssPropsToString({
    padding: '40px 24px',
    textAlign: 'center',
    ...style,
  });

  const headingHtml = heading
    ? `<h3 style="font-size:22px;font-weight:600;color:#1f2937;margin-bottom:20px;font-family:Inter,sans-serif">${esc(heading)}</h3>`
    : '';

  const formStyle = cssPropsToString({
    display: 'flex',
    flexDirection: isInline ? 'row' : 'column',
    gap: isInline ? '0' : '12px',
    maxWidth: isInline ? '480px' : '360px',
    margin: '0 auto',
    alignItems: 'stretch',
  });

  const inputStyleStr = `flex:1;padding:12px 16px;font-size:15px;font-family:Inter,sans-serif;border:1px solid #d1d5db;border-radius:${isInline ? '8px 0 0 8px' : '8px'};background-color:#ffffff;color:#1f2937;outline:none;box-sizing:border-box`;

  const btnStyle = cssPropsToString({
    padding: '12px 24px',
    fontSize: '15px',
    fontWeight: '600',
    fontFamily: 'Inter, sans-serif',
    color: '#ffffff',
    backgroundColor: buttonColor,
    border: 'none',
    borderRadius: isInline ? '0 8px 8px 0' : '8px',
    cursor: 'pointer',
    whiteSpace: 'nowrap',
  });

  return {
    html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
  ${headingHtml}
  <form method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
    <input type="email" name="email" placeholder="${esc(placeholder)}" required style="${inputStyleStr}" />
    <button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${esc(buttonText)}</button>
  </form>
</div>`,
  };
};
