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

interface FormContainerProps {
  action?: string;
  method?: 'GET' | 'POST';
  style?: CSSProperties;
  children?: React.ReactNode;
}

export const FormContainer: UserComponent<FormContainerProps> = ({
  action = '#',
  method = 'POST',
  style = {},
}) => {
  const { connectors: { connect, drag } } = useNode();

  return (
    <form
      ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
      action={action}
      method={method}
      onSubmit={(e) => e.preventDefault()}
      style={{
        padding: '24px',
        minHeight: '80px',
        ...style,
      }}
    >
      <Element
        id="form-inner"
        is={Container}
        canvas
        style={{ display: 'flex', flexDirection: 'column', gap: '16px', padding: '0' }}
        tag="div"
      />
    </form>
  );
};

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

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

  const bgPresets = ['#ffffff', '#f8fafc', '#f1f5f9', '#18181b', '#0f172a'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Form Action URL</label>
        <input
          type="text"
          value={props.action || ''}
          onChange={(e) => setProp((p: FormContainerProps) => { p.action = e.target.value; })}
          placeholder="https://... or /api/submit"
          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 }}>Method</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {(['GET', 'POST'] as const).map((m) => (
            <button
              key={m}
              onClick={() => setProp((p: FormContainerProps) => { p.method = m; })}
              style={{
                padding: '4px 12px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.method === m ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {m}
            </button>
          ))}
        </div>
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Background</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {bgPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: FormContainerProps) => { 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 ---------- */

FormContainer.craft = {
  displayName: 'Form',
  props: {
    action: '#',
    method: 'POST',
    style: {
      padding: '24px',
      backgroundColor: '#ffffff',
      borderRadius: '8px',
      border: '1px solid #e4e4e7',
    },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: FormContainerSettings,
  },
};

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

(FormContainer as any).toHtml = (props: FormContainerProps, childrenHtml: string) => {
  const styleStr = cssPropsToString({
    padding: '24px',
    ...props.style,
  });
  return {
    html: `<form action="${props.action || '#'}" method="${props.method || 'POST'}"${styleStr ? ` style="${styleStr}"` : ''}>${childrenHtml}</form>`,
  };
};
