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

interface FormContainerProps {
  action?: string;
  method?: 'GET' | 'POST';
  recipientEmail?: string;
  thankYouUrl?: string;
  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 }}>Send submissions to (email)</label>
        <input
          type="email"
          value={props.recipientEmail || ''}
          onChange={(e) => setProp((p: FormContainerProps) => { p.recipientEmail = e.target.value; })}
          placeholder="you@example.com"
          style={{ width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12 }}
        />
        <p style={{ fontSize: 10, color: '#71717a', margin: '4px 0 0' }}>
          Delivered via the site's contact-form relay. Requires the relay to be enabled on this server. Leave blank to use the Form Action URL below instead.
        </p>
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Thank-you page URL (optional)</label>
        <input
          type="text"
          value={props.thankYouUrl || ''}
          onChange={(e) => setProp((p: FormContainerProps) => { p.thankYouUrl = e.target.value; })}
          placeholder="/thank-you (blank = hosted page)"
          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 }}>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',
    recipientEmail: '',
    thankYouUrl: '',
    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,
  });
  const { useRelay, marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, props.action);
  const method = useRelay ? 'POST' : (props.method || 'POST'); // relay requires POST
  const body = honeypot + childrenHtml;                        // honeypot as first child
  return {
    html: `${marker}<form action="${actionAttr}" method="${method}"${styleStr ? ` style="${styleStr}"` : ''}>${body}</form>`,
  };
};
