import { ComponentType, FunctionComponent, SVGAttributes } from 'react';
import { APP_ICON_SIZE } from '../../config';
import { IconName, ICONS, DIRECTIONAL_ICONS } from './config';

/**
 * Props of the AppIcon component, also can be used for SVG icons
 */
export interface Props extends SVGAttributes<SVGElement> {
  color?: string;
  icon?: IconName | string;
  size?: string | number;
  title?: string;
}

/**
 * Renders SVG icon by given Icon name
 * @component AppIcon
 * @param {string} [color] - color of the icon as a CSS color value
 * @param {string} [icon] - name of the Icon to render
 * @param {string} [title] - title/hint to show when the cursor hovers the icon
 * @param {string | number} [size] - size of the icon, default is ICON_SIZE
 */
const AppIcon: FunctionComponent<Props> = ({
  color,
  icon = 'default',
  size = APP_ICON_SIZE,
  style,
  ...restOfProps
}) => {
  const iconName = (icon || 'default').trim().toLowerCase() as IconName;

  let ComponentToRender: ComponentType = ICONS[iconName];
  if (!ComponentToRender) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn(`AppIcon: icon "${iconName}" is not found!`);
    }
    ComponentToRender = ICONS.default;
  }

  const sizeValue = typeof size === 'number' ? `${size}px` : size;

  // MUI's SvgIcon sets width/height:1em via its own class, which beats plain
  // width/height attributes — driving size through fontSize (the basis for 1em)
  // is what actually resizes MUI-registry icons. Custom raw <svg> icons (the
  // brand mark) aren't MUI SvgIcon-based, so they keep scaling off the explicit
  // width/height attributes below; the extra fontSize style is harmless for them.
  const propsToRender = {
    height: size,
    width: size,
    color,
    fill: color && 'currentColor',
    style: { ...style, color, fontSize: sizeValue },
    ...restOfProps,
  };

  // Directional icons (back/chevron_start, …) are authored for LTR and mirror
  // under RTL via the single CSS rule in tokens.css keyed on this attribute —
  // registering a name in DIRECTIONAL_ICONS (config.ts) is the only step a
  // later phase needs; never hand-roll a flip at the call site.
  const directionalProps = DIRECTIONAL_ICONS.has(iconName) ? { 'data-icon-directional': true } : undefined;

  return <ComponentToRender data-icon={iconName} {...directionalProps} {...propsToRender} />;
};

export default AppIcon;
