import { getColors } from '@/themes/getColors';
import { default as MuiAvatar } from '@mui/material/Avatar';
import { Theme, styled, useTheme } from '@mui/material/styles';
import { PropsWithChildren } from 'react';

type GetColorStyleProps = {
  theme: any;
  color: string;
  type: 'filled' | 'outlined' | 'combined';
};

function getColorStyle({ theme, color, type }: GetColorStyleProps) {
  const colors = getColors(theme, color as any);
  // @ts-ignore
  const { lighter, light, main, contrastText } = colors;

  switch (type) {
    case 'filled':
      return {
        color: contrastText,
        backgroundColor: main
      };
    case 'outlined':
      return {
        color: main,
        border: '1px solid',
        borderColor: main,
        backgroundColor: 'transparent'
      };
    case 'combined':
      return {
        color: main,
        border: '1px solid',
        borderColor: light,
        backgroundColor: lighter
      };
    default:
      return {
        color: main,
        backgroundColor: lighter
      };
  }
}

function getSizeStyle(size: 'badge' | 'xs' | 'sm' | 'md' | 'lg' | 'xl') {
  switch (size) {
    case 'badge':
      return {
        border: '2px solid',
        fontSize: '0.675rem',
        width: 20,
        height: 20
      };
    case 'xs':
      return {
        fontSize: '0.75rem',
        width: 24,
        height: 24
      };
    case 'sm':
      return {
        fontSize: '0.875rem',
        width: 32,
        height: 32
      };
    case 'lg':
      return {
        fontSize: '1.2rem',
        width: 52,
        height: 52
      };
    case 'xl':
      return {
        fontSize: '1.5rem',
        width: 64,
        height: 64
      };
    case 'md':
    default:
      return {
        fontSize: '1rem',
        width: 40,
        height: 40
      };
  }
}
type AvatarStyleProps = {
  variant: 'circular' | 'rounded' | 'square';
  color: string;
  type: 'filled' | 'outlined' | 'combined';
  size: 'badge' | 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  theme: Theme;
};

const AvatarStyle = styled(MuiAvatar, {
  shouldForwardProp: (prop) => prop !== 'color' && prop !== 'type' && prop !== 'size'
})(({ theme, color, type, size }: AvatarStyleProps) => ({
  ...getSizeStyle(size),
  ...getColorStyle({ theme, color, type }),
  ...(size === 'badge' && {
    borderColor: theme.palette.background.default
  })
}));

type AvatarProps = PropsWithChildren<{
  color: string;
  type: 'filled' | 'outlined' | 'combined';
  size: 'badge' | 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  variant: 'circular' | 'rounded' | 'square';
}>;

function Avatar({ variant = 'circular', children, color = 'primary', type, size = 'md', ...others }: AvatarProps) {
  const theme = useTheme();

  return (
    <AvatarStyle variant={variant} theme={theme} color={color} type={type} size={size} {...others}>
      {children}
    </AvatarStyle>
  );
}

export { Avatar };
export type { AvatarProps };
