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

interface InputFieldProps {
  label?: string;
  type?: 'text' | 'email' | 'password' | 'number' | 'tel' | 'url';
  name?: string;
  placeholder?: string;
  required?: boolean;
  style?: CSSProperties;
}

export const InputField: UserComponent<InputFieldProps> = ({
  label = 'Label',
  type = 'text',
  name = 'field',
  placeholder = '',
  required = false,
  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={{
        display: 'flex',
        flexDirection: 'column',
        gap: '4px',
        outline: selected ? '2px solid #3b82f6' : 'none',
        borderRadius: '4px',
        ...style,
      }}
    >
      {label && (
        <label style={{ fontSize: '14px', fontWeight: '500', color: '#18181b' }}>
          {label}{required && <span style={{ color: '#ef4444' }}> *</span>}
        </label>
      )}
      <input
        type={type}
        name={name}
        placeholder={placeholder}
        required={required}
        style={{
          padding: '10px 12px',
          border: '1px solid #d4d4d8',
          borderRadius: '6px',
          fontSize: '14px',
          color: '#18181b',
          backgroundColor: '#ffffff',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
        }}
        readOnly
      />
    </div>
  );
};

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

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

  const typeOptions: InputFieldProps['type'][] = ['text', 'email', 'password', 'number', 'tel', 'url'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Label</label>
        <input
          type="text"
          value={props.label || ''}
          onChange={(e) => setProp((p: InputFieldProps) => { p.label = e.target.value; })}
          style={{ width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12 }}
        />
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Type</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {typeOptions.map((t) => (
            <button
              key={t}
              onClick={() => setProp((p: InputFieldProps) => { p.type = t; })}
              style={{
                padding: '3px 8px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.type === t ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {t}
            </button>
          ))}
        </div>
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Name</label>
        <input
          type="text"
          value={props.name || ''}
          onChange={(e) => setProp((p: InputFieldProps) => { p.name = e.target.value; })}
          style={{ width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12 }}
        />
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Placeholder</label>
        <input
          type="text"
          value={props.placeholder || ''}
          onChange={(e) => setProp((p: InputFieldProps) => { p.placeholder = e.target.value; })}
          style={{ width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12 }}
        />
      </div>

      <div>
        <label style={{ fontSize: 10, color: '#a1a1aa', display: 'flex', alignItems: 'center', gap: 6 }}>
          <input
            type="checkbox"
            checked={!!props.required}
            onChange={(e) => setProp((p: InputFieldProps) => { p.required = e.target.checked; })}
          />
          Required
        </label>
      </div>
    </div>
  );
};

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

InputField.craft = {
  displayName: 'Input',
  props: {
    label: 'Your Name',
    type: 'text',
    name: 'name',
    placeholder: 'Enter your name',
    required: false,
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: InputFieldSettings,
  },
};

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

(InputField as any).toHtml = (props: InputFieldProps, _childrenHtml: string) => {
  const esc = (s: any) => String(s ?? "").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  const wrapStyle = cssPropsToString({
    display: 'flex',
    flexDirection: 'column',
    gap: '4px',
    ...props.style,
  });
  const reqAttr = props.required ? ' required' : '';
  const labelHtml = props.label
    ? `<label style="font-size:14px;font-weight:500;color:#18181b">${esc(props.label)}${props.required ? '<span style="color:#ef4444"> *</span>' : ''}</label>`
    : '';
  return {
    html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
  ${labelHtml}
  <input type="${props.type || 'text'}" name="${esc(props.name || 'field')}" placeholder="${esc(props.placeholder || '')}"${reqAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
</div>`,
  };
};
