import React from 'react';
import { TouchableOpacity } from 'react-native';
import {
  useRestyle,
  spacing,
  border,
  backgroundColor,
  createVariant,
  VariantProps,
  createRestyleComponent,
} from '@shopify/restyle';
import { colors, Theme } from './../../theme/theme';
import { Box } from '../Box';
import { Badge } from '../Badge';
import CartIcon from '../../icons/CartIcon';
import { Normalize } from '../../utils/normalize';

type ButtonProps = React.ComponentProps<typeof ButtonContainer> & {
  /**
   * @defaultValue
   * 0
   */
  quantity?: number;
  onPress: () => void;
};

const restyleFunctions = [spacing, backgroundColor, border];

const ButtonContainer = createRestyleComponent<
  VariantProps<Theme, 'buttonVariants'> &
    React.ComponentProps<typeof Box> & {
      disabled?: boolean;
    },
  Theme
>(
  [
    createVariant({
      themeKey: 'buttonVariants',
    }),
  ],
  Box
);

/**
 * The button allow users to perform action and choice with a single touch and show the amount items in cart.
 * @param {number} onPress - Called when the touch is released, but not if cancelled
 * @param {number} quantity - Amount items in cart
 * @see https://zeroheight.com/502cb86ad/p/281e3e-buttons/t/349477
 */

export const CartButton: React.FC<ButtonProps> = ({
  onPress = () => console.warn('onPress is a required field'),
  disabled,
  quantity = 0,
  ...rest
}) => {
  const props = useRestyle(restyleFunctions, rest);

  const variant = quantity > 0 ? 'primary' : 'light';

  return (
    <TouchableOpacity testID="CartButton" onPress={onPress} disabled={disabled}>
      <ButtonContainer
        variant={disabled ? 'disabled' : variant}
        minHeight={36}
        width={40}
        justifyContent="center"
        alignItems="center"
        flexDirection="row"
        borderRadius={Normalize(4)}
        {...props}
      >
        <CartIcon
          stroke={variant === 'light' ? colors.yankeesBlue : colors.white}
          width={24}
          height={24}
        />
        <Box position="absolute" right={0} top={0}>
          <Badge variant={variant} amount={quantity} />
        </Box>
      </ButtonContainer>
    </TouchableOpacity>
  );
};
