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

interface TextareaFieldProps {
  label?: string;
  name?: string;
  placeholder?: string;
  rows?: number;
  required?: boolean;
  style?: CSSProperties;
}

export const TextareaField: UserComponent<TextareaFieldProps> = ({
  label = 'Message',
  name = 'message',
  placeholder = '',
  rows = 4,
  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>
      )}
      <textarea
        name={name}
        placeholder={placeholder}
        rows={rows}
        required={required}
        readOnly
        style={{
          padding: '10px 12px',
          border: '1px solid #d4d4d8',
          borderRadius: '6px',
          fontSize: '14px',
          color: '#18181b',
          backgroundColor: '#ffffff',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          resize: 'vertical',
          fontFamily: 'inherit',
        }}
      />
    </div>
  );
};

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

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

  const rowsPresets = [2, 3, 4, 6, 8];

  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: TextareaFieldProps) => { 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 }}>Name</label>
        <input
          type="text"
          value={props.name || ''}
          onChange={(e) => setProp((p: TextareaFieldProps) => { 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: TextareaFieldProps) => { 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: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Rows</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {rowsPresets.map((r) => (
            <button
              key={r}
              onClick={() => setProp((p: TextareaFieldProps) => { p.rows = r; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.rows === r ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {r}
            </button>
          ))}
        </div>
      </div>

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

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

TextareaField.craft = {
  displayName: 'Textarea',
  props: {
    label: 'Message',
    name: 'message',
    placeholder: 'Enter your message',
    rows: 4,
    required: false,
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: TextareaFieldSettings,
  },
};

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

(TextareaField as any).toHtml = (props: TextareaFieldProps, _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}
  <textarea name="${esc(props.name || 'message')}" placeholder="${esc(props.placeholder || '')}" rows="${props.rows || 4}"${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;resize:vertical;font-family:inherit"></textarea>
</div>`,
  };
};
