import { ComponentType, CSSProperties, FunctionComponent } from 'react';
import { APP_ICON_SIZE, APP_ICON_STROKE_WIDTH } from '../../config';
import { IconName, ICONS, DIRECTIONAL_ICONS } from './config';
import { IconProps } from './utils';

/**
 * Props of the AppIcon component, also can be used for SVG icons
 */
export interface Props extends IconProps {
  icon?: IconName | 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 APP_ICON_SIZE
 * @param {string | number} [strokeWidth] - Lucide stroke weight, default is APP_ICON_STROKE_WIDTH
 */
const AppIcon: FunctionComponent<Props> = ({
  color,
  icon = 'default',
  size = APP_ICON_SIZE,
  strokeWidth = APP_ICON_STROKE_WIDTH,
  style,
  ...restOfProps
}) => {
  const iconName = (icon || 'default').trim().toLowerCase() as IconName;

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

  // Lucide renders a stroked (never filled) <svg> sized off real width/height attributes, so
  // `size` alone is authoritative — the old fontSize/1em dance MUI's SvgIcon needed is gone.
  // `flexShrink: 0` is the house default because an icon squashed by a flex sibling is the one
  // layout bug this component was silently reintroducing on every narrow row; a caller can still
  // override it through `style`.
  const styleToRender: CSSProperties = { flexShrink: 0, ...style, ...(color ? { color } : null) };

  // Directional icons (back/chevron_start, …) are authored for LTR and mirror
  // under RTL via the single CSS rule in globals.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}
      size={size}
      color={color}
      strokeWidth={strokeWidth}
      style={styleToRender}
      {...restOfProps}
    />
  );
};

export default AppIcon;
