import { colord } from 'colord';
import type { SvgIconProps } from '@mui/material';
import { styled } from '@mui/material';
import type { Palette, PaletteColor } from '@mui/material/styles';

const OverrideSvgIcon = styled('svg', {
  shouldForwardProp: (prop: string) => !['htmlColor', 'color'].includes(prop),
})<SvgIconProps>(({ theme, color, htmlColor }) => {
  const styles: { [key: string]: string } = {};

  const color$ = (color || htmlColor || '') as keyof Palette;

  const drilledProp = color$.split('.');

  if (colord(color$).isValid()) {
    styles.color = color$;
  } else if (drilledProp.length > 1) {
    styles.color = drilledProp.reduce((acc: Palette | PaletteColor | string, key) => {
      const colorKey = key as keyof typeof acc;
      const colorGroup = acc[colorKey];

      if (!colorGroup) {
        if (process.env.NODE_ENV === 'development') {
          throw Error(`Color => ${styles.color} <= doesn't exist in the theme palette`);
        }

        return 'inherit';
      }

      return colorGroup as typeof colorGroup;
    }, theme.palette) as string;
  } else {
    const paletteColor = theme.palette[color$] as PaletteColor;
    styles.color = paletteColor?.main ?? color$;
  }

  return styles;
});

export default OverrideSvgIcon;
