import React from 'react';
import { Box } from '../Box';
import { Text } from '../Text';
import type { theme, Theme } from './../../theme/theme';
import {
  createVariant,
  VariantProps,
  createRestyleComponent,
} from '@shopify/restyle';
import { useTheme } from '../../theme/ThemeProvider';
import { isEmpty } from '../../utils';

export type BadgeProps = React.ComponentProps<typeof BadgeContainer> & {
  amount?: number;
  type?: TypeBadge;
};

export type TypeBadge = 'dot' | 'normal';

const BadgeContainer = createRestyleComponent<
  VariantProps<Theme, 'badgeVariants'> & React.ComponentProps<typeof Box>,
  Theme
>(
  [
    createVariant({
      themeKey: 'badgeVariants',
    }),
  ],
  Box
);

const colorText: {
  [key in keyof typeof theme.badgeVariants]: keyof typeof theme.colors;
} = {
  primary: 'white',
  danger: 'white',
  disabled: 'yankeesBlue',
  outlined: 'darkBlueGray',
  outlinedPrimary: 'green',
  light: 'darkBlueGray',
};

export const Badge: React.FC<BadgeProps> = ({
  variant = 'primary',
  type = 'normal',
  amount = 0,
  ...restProps
}) => {
  const { fonts } = useTheme();
  const widthLarge = 9 * amount.toString().length;
  const width = type === 'dot' ? 8 : amount > 99 ? widthLarge : 16;
  const height = type === 'dot' ? 8 : 16;

  let fontColor: keyof typeof theme.colors = 'white';
  if (typeof variant !== 'object' && variant) {
    fontColor = colorText[variant];
  }

  return (
    <Box
      overflow={'hidden'}
      position={'relative'}
      justifyContent={'center'}
      alignItems={'center'}
    >
      <BadgeContainer
        overflow={'hidden'}
        position={'relative'}
        justifyContent={'center'}
        width={width}
        height={height}
        borderRadius={8}
        alignItems={'center'}
        variant={variant}
        {...restProps}
      >
        {type !== 'dot' && !isEmpty(amount) && (
          <Text
            fontFamily={fonts.caustenRoundBold}
            fontSize={12}
            color={fontColor}
          >
            {amount}
          </Text>
        )}
      </BadgeContainer>
    </Box>
  );
};
