import styles from './index.module.scss';
import { Icon as CMSIcon } from '@hubspot/cms-components';
import ContentFields from './ContentFields.js';
import StyleFields from './StyleFields.js';
import cx from '../utils/classname.js';
import { IconProps } from './types.js';

const ICON_SIZE_MAP: Record<string, number> = {
  small: 16,
  medium: 24,
  large: 32,
};

const ICON_SHAPE_MAP: Record<string, string> = {
  square: '0px',
  rounded: '8px',
  circle: '100%',
};

const IconComponent = ({
  fieldPath,
  showIcon = true,
  size,
  className = '',
  style = {},
  purpose = 'DECORATIVE',
  title = '',
  fill,
  showIconBackground = false,
  iconBackgroundColor,
  iconBackgroundPadding,
  iconBackgroundShape,
}: IconProps) => {
  if (!showIcon) return null;

  const resolvedSize = size ? ICON_SIZE_MAP[size] : undefined;
  const resolvedShape = iconBackgroundShape
    ? ICON_SHAPE_MAP[iconBackgroundShape] ?? iconBackgroundShape
    : undefined;

  const iconStyle: React.CSSProperties = {
    ...(fill && { fill }),
    ...(resolvedSize !== undefined && {
      width: `${resolvedSize}px`,
      height: `${resolvedSize}px`,
    }),
    ...style,
  };

  const defaultClasses = styles.icon;
  const combinedClasses = cx(defaultClasses, className);

  const icon = (
    <CMSIcon
      fieldPath={fieldPath}
      height={resolvedSize}
      className={combinedClasses}
      style={iconStyle}
      purpose={purpose}
      title={title}
    />
  );

  if (!showIconBackground) return icon;

  const backgroundStyle: React.CSSProperties = {
    ...(iconBackgroundColor && { backgroundColor: iconBackgroundColor }),
    ...(iconBackgroundPadding && {
      padding: `${iconBackgroundPadding}px`,
    }),
    ...(resolvedShape && { borderRadius: resolvedShape }),
  };

  return (
    <div className={styles.iconBackground} style={backgroundStyle}>
      {icon}
    </div>
  );
};

type IconComponentType = typeof IconComponent & {
  ContentFields: typeof ContentFields;
  StyleFields: typeof StyleFields;
};

const Icon = IconComponent as IconComponentType;
Icon.ContentFields = ContentFields;
Icon.StyleFields = StyleFields;

export default Icon;
