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

interface MapEmbedProps {
  address?: string;
  zoom?: number;
  height?: string;
  style?: CSSProperties;
}

function buildMapUrl(address: string, zoom: number): string {
  const encoded = encodeURIComponent(address);
  return `https://maps.google.com/maps?q=${encoded}&z=${zoom}&output=embed`;
}

export const MapEmbed: UserComponent<MapEmbedProps> = ({
  address = 'New York, NY',
  zoom = 14,
  height = '400px',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  return (
    <div
      ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        width: '100%',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      <iframe
        src={buildMapUrl(address, zoom)}
        style={{
          width: '100%',
          height,
          border: 'none',
          borderRadius: (style as any)?.borderRadius || '0px',
          display: 'block',
        }}
        loading="lazy"
        referrerPolicy="no-referrer-when-downgrade"
        allowFullScreen
      />
    </div>
  );
};

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

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

  const labelStyle: CSSProperties = { fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 };
  const inputStyle: CSSProperties = {
    width: '100%', padding: '4px 8px', background: '#27272a', color: '#e4e4e7',
    border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12,
  };

  const heightPresets = ['300px', '400px', '500px', '600px'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Address */}
      <div>
        <label style={labelStyle}>Address</label>
        <input
          type="text"
          value={props.address || ''}
          onChange={(e) => setProp((p: MapEmbedProps) => { p.address = e.target.value; })}
          placeholder="Enter an address or location..."
          style={inputStyle}
        />
      </div>

      {/* Zoom */}
      <div>
        <label style={labelStyle}>Zoom: {props.zoom || 14}</label>
        <input
          type="range"
          min={1}
          max={20}
          value={props.zoom || 14}
          onChange={(e) => setProp((p: MapEmbedProps) => { p.zoom = parseInt(e.target.value, 10); })}
          style={{ width: '100%' }}
        />
      </div>

      {/* Height */}
      <div>
        <label style={labelStyle}>Height</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 6 }}>
          {heightPresets.map((h) => (
            <button
              key={h}
              onClick={() => setProp((p: MapEmbedProps) => { p.height = h; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.height === h ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {h}
            </button>
          ))}
        </div>
        <input
          type="text"
          value={props.height || ''}
          onChange={(e) => setProp((p: MapEmbedProps) => { p.height = e.target.value; })}
          placeholder="e.g. 400px"
          style={inputStyle}
        />
      </div>
    </div>
  );
};

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

MapEmbed.craft = {
  displayName: 'Map',
  props: {
    address: 'New York, NY',
    zoom: 14,
    height: '400px',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: MapEmbedSettings,
  },
};

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

(MapEmbed as any).toHtml = (props: MapEmbedProps, _childrenHtml: string) => {
  const {
    address = 'New York, NY',
    zoom = 14,
    height = '400px',
    style = {},
  } = props;

  const wrapperStyle = cssPropsToString({ width: '100%', ...style });
  const iframeStyle = cssPropsToString({
    width: '100%',
    height,
    border: 'none',
    borderRadius: (style as any)?.borderRadius || undefined,
    display: 'block',
  });

  const src = buildMapUrl(address, zoom);

  return {
    html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}><iframe src="${src}" loading="lazy" referrerpolicy="no-referrer-when-downgrade" allowfullscreen${iframeStyle ? ` style="${iframeStyle}"` : ''}></iframe></div>`,
  };
};
