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

interface BackgroundSectionProps {
  bgImage?: string;
  bgColor?: string;
  overlayColor?: string;
  overlayOpacity?: number;
  innerMaxWidth?: string;
  style?: CSSProperties;
  children?: React.ReactNode;
  anchorId?: string;
}

export const BackgroundSection: UserComponent<BackgroundSectionProps> = ({
  bgImage = '',
  bgColor = '#1e293b',
  overlayColor = '#000000',
  overlayOpacity = 0.4,
  innerMaxWidth = '1200px',
  style = {},
  anchorId,
}) => {
  const { connectors: { connect, drag } } = useNode();

  return (
    <section
      ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
      id={anchorId || undefined}
      style={{
        position: 'relative',
        width: '100%',
        minHeight: '200px',
        backgroundColor: bgColor,
        backgroundImage: bgImage ? `url(${bgImage})` : undefined,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        ...style,
      }}
    >
      {/* Overlay */}
      <div
        style={{
          position: 'absolute',
          inset: 0,
          backgroundColor: overlayColor,
          opacity: overlayOpacity,
          pointerEvents: 'none',
        }}
      />
      {/* Content */}
      <Element
        id="bg-section-inner"
        is={Container}
        canvas
        style={{
          position: 'relative',
          zIndex: 1,
          maxWidth: innerMaxWidth,
          margin: '0 auto',
          padding: '60px 20px',
        }}
        tag="div"
      />
    </section>
  );
};

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

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

  const bgColorPresets = ['#1e293b', '#0f172a', '#18181b', '#1e3a5f', '#312e81', '#064e3b', '#7f1d1d', '#ffffff'];
  const overlayPresets = ['#000000', '#1e293b', '#0f172a', '#312e81', '#064e3b', '#7f1d1d'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <AnchorIdField />
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Background Image URL</label>
        <input
          type="text"
          value={props.bgImage || ''}
          onChange={(e) => setProp((p: BackgroundSectionProps) => { p.bgImage = e.target.value; })}
          placeholder="https://... or /storage/assets/..."
          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 }}>Background Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {bgColorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: BackgroundSectionProps) => { p.bgColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.bgColor === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Overlay Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {overlayPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: BackgroundSectionProps) => { p.overlayColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.overlayColor === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>
          Overlay Opacity: {Math.round((props.overlayOpacity ?? 0.4) * 100)}%
        </label>
        <input
          type="range"
          min={0}
          max={100}
          value={Math.round((props.overlayOpacity ?? 0.4) * 100)}
          onChange={(e) => setProp((p: BackgroundSectionProps) => { p.overlayOpacity = parseInt(e.target.value, 10) / 100; })}
          style={{ width: '100%' }}
        />
      </div>

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

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

BackgroundSection.craft = {
  displayName: 'Background Section',
  props: {
    bgImage: '',
    bgColor: '#1e293b',
    overlayColor: '#000000',
    overlayOpacity: 0.4,
    innerMaxWidth: '1200px',
    style: { padding: '0' },
    anchorId: '',
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: BackgroundSectionSettings,
  },
};

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

(BackgroundSection as any).toHtml = (props: BackgroundSectionProps, childrenHtml: string) => {
  const esc = (s: any) => String(s ?? "").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  const outerStyle = cssPropsToString({
    position: 'relative',
    width: '100%',
    minHeight: '200px',
    backgroundColor: props.bgColor || '#1e293b',
    backgroundImage: props.bgImage ? `url(${props.bgImage})` : undefined,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
    ...props.style,
  });
  const overlayStyle = cssPropsToString({
    position: 'absolute',
    inset: '0',
    backgroundColor: props.overlayColor || '#000000',
    opacity: String(props.overlayOpacity ?? 0.4),
    pointerEvents: 'none',
  });
  const innerStyle = cssPropsToString({
    position: 'relative',
    zIndex: '1',
    maxWidth: props.innerMaxWidth || '1200px',
    margin: '0 auto',
    padding: '60px 20px',
  });
  const idAttr = props.anchorId ? ` id="${esc(props.anchorId)}"` : '';
  return {
    html: `<section${idAttr}${outerStyle ? ` style="${outerStyle}"` : ''}><div${overlayStyle ? ` style="${overlayStyle}"` : ''}></div><div${innerStyle ? ` style="${innerStyle}"` : ''}>${childrenHtml}</div></section>`,
  };
};
