import React, { FunctionComponent } from 'react';
import { SvgIconComponent } from '@mui/icons-material';
import { iconsSVG } from './Svgs';
import { IconColors, IconScale } from '../types';
import { IconsProps, SvgProps } from '../interfaces/Icons';
import styled from '@emotion/styled';
import { palette } from '../helpers';

export const Svg = styled.svg<SvgProps>(
  {
    shapeRendering: 'inherit',
    transform: 'translate3d(0,0,0)',
  },
  ({ inline }) => (inline ? { display: 'inline-block' } : { display: 'block' }),
);

const scaleSize: Partial<Record<IconScale, number>> = {
  xsmall: 14,
  small: 20,
  medium: 24,
  large: 28,
  xlarge: 32,
  '2xlarge': 36,
  '3xlarge': 40,
};

const colors: Record<IconColors, string> = {
  inherit: palette.inherit,
  primary: palette.primary,
  secondary: palette.secondary,
  error: palette.error,
  info: palette.info,
  success: palette.success,
  warning: palette.warning,
  white: palette.white,
  black: palette.black,
};


export const Icons: FunctionComponent<IconsProps> = ({
  icon,
  scale,
  useSymbol,
  color = 'inherit',
  ...props
}: IconsProps) => {
  let width = 24;
  let height = 24;
  if (scale) {
    width = scaleSize[scale] || 24;
    height = scaleSize[scale] || 24;
  }

  const fill = colors[color] || color;
  const stroke = colors[color] || color;

  const Svg = styled.svg`
    display: inline-block;
    shape-rendering: inherit;
    vertical-align: middle;
    fill: ${fill};
    path {
      stroke: ${stroke};
    }
    circle {
      stroke: ${stroke};
    }
    rect {
      stroke: ${stroke};
    }
  `;

  const isMuiIcon = typeof icon !== 'string';

  return (
    <Svg viewBox="0 0 56 56" width={`${width}px`} height={`${height}px`} {...props}>
      {useSymbol ? (
        <use xlinkHref={`#icon--${icon}`} fill={fill} stroke={stroke} />
      ) : isMuiIcon ? (
        React.createElement(icon as SvgIconComponent, { style: { fill, stroke } })
      ) : (
        React.cloneElement(iconsSVG[icon], { fill, stroke })
      )}
    </Svg>
  );
};