import { forwardRef, memo } from 'react';
import type { FC, ForwardedRef } from 'react';
import { ReactSVG } from 'react-svg';
import clsx from 'clsx';

import { styled } from '@mui/material/styles';
import type { Theme } from '../@styles/theme-provider';

import type { CustomIconProps } from './types';

interface StyledReactSVGProps {
  color?: CustomIconProps['color'];
  customSize?: CustomIconProps['customSize'];
  rotateDeg?: CustomIconProps['rotateDeg'];
}

const StyledReactSVG = styled(ReactSVG, {
  shouldForwardProp: prop =>
    prop !== 'color' && prop !== 'customSize' && prop !== 'rotateDeg' && prop !== 'sx'
})<StyledReactSVGProps>(
  ({ color, customSize, rotateDeg, theme }: StyledReactSVGProps & { theme: Theme }) => ({
    color,
    lineHeight: 0,
    display: 'inline-flex',
    alignItems: 'center',
    flexShrink: 0,
    justifyContent: 'center',
    minWidth: 0,
    overflow: 'hidden',
    '& > div': {
      display: 'flex',
      pointerEvents: 'none',
      ...(customSize && {
        width: customSize,
        height: customSize
      }),
      ...(rotateDeg && {
        transform: `rotate(${rotateDeg}deg)`
      })
    },
    '& .injected-svg': {
      display: 'flex',
      width: '100%',
      height: '100%',
      userSelect: 'none'
    },
    '&.inheritColor': {
      '& > div': {
        color: 'inherit'
      },
      '& .injected-svg path': {
        fill: 'currentColor'
      }
    },
    '&.small > div': {
      width: theme.spacing(2),
      height: theme.spacing(2)
    },
    '&.medium > div': {
      width: theme.spacing(2.5),
      height: theme.spacing(2.5)
    },
    '&.large > div': {
      width: theme.spacing(3),
      height: theme.spacing(3)
    },
    '&.xlarge > div': {
      width: theme.spacing(4),
      height: theme.spacing(4)
    }
  })
);

const CustomIcon: FC<CustomIconProps> = forwardRef(
  (props: CustomIconProps, ref: ForwardedRef<null>) => {
    const { color = '#546491', size = 'small', customSize, className, ...otherProps } = props;
    return (
      <StyledReactSVG
        ref={ref}
        useRequestCache
        wrapper="div"
        {...otherProps}
        color={color}
        customSize={customSize}
        className={clsx(color && 'inheritColor', !customSize && size, className)}
      />
    );
  }
);

const m = memo(CustomIcon);
export { m as CustomIcon };
