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

interface FooterProps {
  text?: string;
  style?: CSSProperties;
}

export const Footer: UserComponent<FooterProps> = ({
  text = '© 2026 MySite. All rights reserved.',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
    actions: { setProp },
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  const elRef = useRef<HTMLElement | null>(null);

  const handleBlur = useCallback(() => {
    if (elRef.current) {
      const newText = elRef.current.innerText;
      setProp((p: FooterProps) => { p.text = newText; }, 500);
    }
  }, [setProp]);

  useEffect(() => {
    if (elRef.current && !selected) {
      elRef.current.innerText = text || '';
    }
  }, [text, selected]);

  return (
    <footer
      ref={(ref: HTMLElement | null): void => {
        elRef.current = ref;
        if (ref) connect(drag(ref));
      }}
      contentEditable={selected}
      suppressContentEditableWarning
      onBlur={handleBlur}
      style={{
        padding: '24px 20px',
        textAlign: 'center',
        outline: 'none',
        cursor: selected ? 'text' : 'pointer',
        ...style,
      }}
    >
      {selected ? undefined : (text || '')}
    </footer>
  );
};

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

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

  const bgPresets = ['#ffffff', '#f8fafc', '#18181b', '#0f172a', '#1e293b'];
  const colorPresets = ['#18181b', '#3f3f46', '#71717a', '#a1a1aa', '#e4e4e7', '#ffffff'];

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

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

Footer.craft = {
  displayName: 'Footer',
  props: {
    text: '© 2026 MySite. All rights reserved.',
    style: {
      backgroundColor: '#18181b',
      color: '#a1a1aa',
      fontSize: '14px',
      padding: '24px 20px',
    },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: FooterSettings,
  },
};

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

(Footer as any).toHtml = (props: FooterProps, _childrenHtml: string) => {
  const styleStr = cssPropsToString({
    padding: '24px 20px',
    textAlign: 'center',
    ...props.style,
  });
  const escapedText = (props.text || '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return { html: `<footer${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</footer>` };
};
