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

interface IconProps {
  icon?: string;
  size?: string;
  color?: string;
  bgColor?: string;
  bgShape?: 'none' | 'circle' | 'square' | 'rounded';
  bgSize?: string;
  link?: string;
  style?: CSSProperties;
}

const COMMON_ICONS = [
  'fa-star', 'fa-heart', 'fa-check', 'fa-phone', 'fa-envelope',
  'fa-map-marker', 'fa-globe', 'fa-facebook', 'fa-twitter', 'fa-instagram',
  'fa-linkedin', 'fa-youtube', 'fa-github', 'fa-arrow-right', 'fa-arrow-down',
  'fa-play', 'fa-search', 'fa-user', 'fa-lock', 'fa-cog',
  'fa-home', 'fa-comment', 'fa-camera', 'fa-music', 'fa-shopping-cart',
  'fa-calendar', 'fa-clock-o', 'fa-thumbs-up', 'fa-lightbulb-o', 'fa-rocket',
];

function getBgBorderRadius(shape: string): string {
  if (shape === 'circle') return '50%';
  if (shape === 'rounded') return '8px';
  if (shape === 'square') return '0px';
  return '0px';
}

export const Icon: UserComponent<IconProps> = ({
  icon = 'fa-star',
  size = '32px',
  color = '#3b82f6',
  bgColor = 'transparent',
  bgShape = 'none',
  bgSize = '56px',
  link = '',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  const iconEl = (
    <i
      className={`fa ${icon}`}
      style={{ fontSize: size, color, lineHeight: 1 }}
    />
  );

  const hasBg = bgShape !== 'none' && bgColor !== 'transparent';

  const wrapperEl = hasBg ? (
    <div
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: bgSize,
        height: bgSize,
        backgroundColor: bgColor,
        borderRadius: getBgBorderRadius(bgShape || 'none'),
      }}
    >
      {iconEl}
    </div>
  ) : iconEl;

  const content = link ? (
    <a href={link} onClick={(e) => e.preventDefault()} style={{ textDecoration: 'none', color: 'inherit' }}>
      {wrapperEl}
    </a>
  ) : wrapperEl;

  return (
    <div
      ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        display: 'inline-block',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      {content}
    </div>
  );
};

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

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

  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 sizePresets = ['24px', '32px', '48px', '64px'];
  const colorPresets = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899', '#18181b', '#ffffff'];
  const shapePresets: Array<{ label: string; value: IconProps['bgShape'] }> = [
    { label: 'None', value: 'none' },
    { label: 'Circle', value: 'circle' },
    { label: 'Square', value: 'square' },
    { label: 'Rounded', value: 'rounded' },
  ];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Icon picker */}
      <div>
        <label style={labelStyle}>Icon</label>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 4, maxHeight: 200, overflowY: 'auto' }}>
          {COMMON_ICONS.map((ic) => (
            <button
              key={ic}
              onClick={() => setProp((p: IconProps) => { p.icon = ic; })}
              title={ic}
              style={{
                padding: '6px', fontSize: 16, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.icon === ic ? '#3b82f6' : '#27272a',
                color: props.icon === ic ? '#fff' : '#e4e4e7',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >
              <i className={`fa ${ic}`} />
            </button>
          ))}
        </div>
      </div>

      {/* Custom icon class */}
      <div>
        <label style={labelStyle}>Custom Icon Class</label>
        <input
          type="text"
          value={props.icon || ''}
          onChange={(e) => setProp((p: IconProps) => { p.icon = e.target.value; })}
          placeholder="fa-star"
          style={inputStyle}
        />
      </div>

      {/* Size */}
      <div>
        <label style={labelStyle}>Size</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {sizePresets.map((s) => (
            <button
              key={s}
              onClick={() => setProp((p: IconProps) => { p.size = s; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.size === s ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      {/* Color */}
      <div>
        <label style={labelStyle}>Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {colorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: IconProps) => { p.color = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.color === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Background shape */}
      <div>
        <label style={labelStyle}>Background Shape</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {shapePresets.map((s) => (
            <button
              key={s.value}
              onClick={() => setProp((p: IconProps) => { p.bgShape = s.value; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.bgShape === s.value ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {/* Background color */}
      {props.bgShape !== 'none' && (
        <div>
          <label style={labelStyle}>Background Color</label>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#18181b', '#f1f5f9', '#ffffff'].map((c) => (
              <button
                key={c}
                onClick={() => setProp((p: IconProps) => { 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>
      )}

      {/* Background size */}
      {props.bgShape !== 'none' && (
        <div>
          <label style={labelStyle}>Background Size</label>
          <input
            type="text"
            value={props.bgSize || '56px'}
            onChange={(e) => setProp((p: IconProps) => { p.bgSize = e.target.value; })}
            placeholder="56px"
            style={inputStyle}
          />
        </div>
      )}

      {/* Link */}
      <div>
        <label style={labelStyle}>Link URL</label>
        <input
          type="text"
          value={props.link || ''}
          onChange={(e) => setProp((p: IconProps) => { p.link = e.target.value; })}
          placeholder="https://..."
          style={inputStyle}
        />
      </div>
    </div>
  );
};

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

Icon.craft = {
  displayName: 'Icon',
  props: {
    icon: 'fa-star',
    size: '32px',
    color: '#3b82f6',
    bgColor: 'transparent',
    bgShape: 'none',
    bgSize: '56px',
    link: '',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: IconSettings,
  },
};

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

(Icon as any).toHtml = (props: IconProps, _childrenHtml: string) => {
  const {
    icon = 'fa-star',
    size = '32px',
    color = '#3b82f6',
    bgColor = 'transparent',
    bgShape = 'none',
    bgSize = '56px',
    link = '',
    style = {},
  } = props;

  const iconStyle = cssPropsToString({ fontSize: size, color, lineHeight: '1' });
  let iconHtml = `<i class="fa ${icon}"${iconStyle ? ` style="${iconStyle}"` : ''}></i>`;

  const hasBg = bgShape !== 'none' && bgColor !== 'transparent';
  if (hasBg) {
    const bgStyle = cssPropsToString({
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      width: bgSize,
      height: bgSize,
      backgroundColor: bgColor,
      borderRadius: getBgBorderRadius(bgShape || 'none'),
    });
    iconHtml = `<div${bgStyle ? ` style="${bgStyle}"` : ''}>${iconHtml}</div>`;
  }

  if (link) {
    iconHtml = `<a href="${link}" style="text-decoration:none;color:inherit">${iconHtml}</a>`;
  }

  const wrapperStyle = cssPropsToString({ display: 'inline-block', ...style });
  return { html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>${iconHtml}</div>` };
};
