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

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,
};

export const Icons: FunctionComponent<IconsProps> = ({
  icon,
  scale,
  useSymbol,
  color = 'inherit',
  ...props
}: IconsProps) => {

  const theme = useTheme()

  const colors: Record<string, string> = {
    primary: theme.palette.primary.main,
    secondary: theme.palette.secondary.main,
    error: theme.palette.error.main,
    info: theme.palette.info.main,
    success: theme.palette.success.main,
    warning: theme.palette.warning.main,
    action: theme.palette.action.disabled,
    inherit: theme.palette.text.primary,
    white: '#ffffff',
    black: '#000000',
  };

  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>
  );
};
