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

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

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

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

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

  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>Header 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: HeaderZoneProps) => { p.style = { ...p.style, backgroundColor: c }; })}
              style={{ width: 28, height: 28, borderRadius: 4, border: '1px solid #3f3f46', background: c, cursor: 'pointer' }}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

HeaderZone.craft = {
  displayName: 'Header Zone',
  props: {
    style: { backgroundColor: '#ffffff' },
  },
  rules: {
    canDrag: () => false, // Header stays at the top, can't be moved
    canMoveIn: () => true,
    canMoveOut: () => true,
  },
  related: {
    settings: HeaderZoneSettings,
  },
};

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