import classNames from "classnames/dedupe";
import type { IconProps } from "./types";
import "./Icon.css";

const ICON_PREFIX = "mobius-icon";

const capitaliseFirstLetter = (str: string) =>
  str.charAt(0).toUpperCase() + str.slice(1);

export function Icon({
  ref,
  icon,
  className,
  size = "xs",
  color,
  fixedWidth,
  spin,
  spinReverse,
  title,
  ...otherProps
}: IconProps) {
  if (!icon) {
    throw new Error("Must specify icon object");
  }

  const classes = classNames(
    "mobius",
    "mobius-icon",
    `svg-inline--${ICON_PREFIX}`,
    `--size-${size}`,
    className,
    {
      [`${ICON_PREFIX}-fw`]: fixedWidth,
      [`${ICON_PREFIX}-spin`]: spin || spinReverse,
      [`${ICON_PREFIX}-spin-reverse`]: spinReverse,
    },
  );

  const { iconName, width, height, svgPathData } = icon;
  const formattedIconName = iconName.split("-").join(" ");

  const defaultTitle = `${capitaliseFirstLetter(formattedIconName)} icon`;
  const titleText = title || defaultTitle;

  return (
    <svg
      ref={ref}
      focusable="false"
      data-icon={iconName}
      className={classes}
      role="img"
      xmlns="http://www.w3.org/2000/svg"
      viewBox={`0 0 ${width} ${height}`}
      style={{ color }}
      {...otherProps}
    >
      <title>{titleText}</title>
      <path fill="currentColor" d={svgPathData} />
    </svg>
  );
}
