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

interface FooterZoneProps {
  style?: CSSProperties;
  children?: React.ReactNode;
}

export const FooterZone: UserComponent<FooterZoneProps> = ({ style = {}, children }) => {
  const { connectors: { connect, drag } } = useNode();

  return (
    <footer
      ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
      data-zone="footer"
      style={{
        width: '100%',
        minHeight: '50px',
        borderTop: '1px solid rgba(148,163,184,0.15)',
        ...style,
      }}
    >
      <Element id="footer-content" is={Container} canvas tag="div" style={{ padding: '0' }}>
        {children}
      </Element>
    </footer>
  );
};

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

  const bgPresets = ['#ffffff', '#f9fafb', '#1f2937', '#111827', '#0f172a'];

  return (
    <div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <p style={{ fontSize: 11, color: '#f59e0b', margin: 0 }}>
        <strong>Footer Zone</strong> -- This section appears on all pages.
      </p>
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 4 }}>Background</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {bgPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: FooterZoneProps) => { p.style = { ...p.style, backgroundColor: c }; })}
              style={{ width: 28, height: 28, borderRadius: 4, border: '1px solid #3f3f46', background: c, cursor: 'pointer' }}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

FooterZone.craft = {
  displayName: 'Footer Zone',
  props: {
    style: { backgroundColor: '#0f172a', color: '#94a3b8', padding: '40px 20px', textAlign: 'center' as const },
  },
  rules: {
    canDrag: () => false,
    canMoveIn: () => true,
    canMoveOut: () => true,
  },
  related: {
    settings: FooterZoneSettings,
  },
};

(FooterZone as any).toHtml = (props: FooterZoneProps, childrenHtml: string) => {
  const styleStr = cssPropsToString({
    width: '100%',
    ...props.style,
  });
  return { html: `<footer${styleStr ? ` style="${styleStr}"` : ''}>${childrenHtml}</footer>` };
};
