import React, { FC, ButtonHTMLAttributes } from 'react';
import styled from 'styled-components';
import { get } from 'lodash';
import { Box } from '../Box';
import { buttonReset, getHoverColor } from '../../styles/utils';
import { getVariant } from './styles';
import { Icon } from '../Icon';

type IconProps = React.ComponentProps<typeof Icon>;
type BoxProps = React.ComponentProps<typeof Box>;

export type variants = 'primary' | 'raw';

export interface Props extends IconProps {
  /**
   * Specify the variant of Button you want to create
   */
  variant?: variants;
  onClick: () => void;
  IconComponent?: React.ComponentType;
  buttonProps?: BoxProps & ButtonHTMLAttributes<HTMLButtonElement>;
}

export const defaultProps = {
  variant: 'raw' as variants,
};

const Button = styled(Box)(buttonReset, getVariant);

const StyledIcon = styled(Icon)(({ theme, color }) => ({
  cursor: 'pointer',

  '&:hover': {
    color: color && getHoverColor(get(theme, `colors.${color}`)),
  },
}));

export const IconButton: FC<Props> = ({
  children,
  className,
  style,
  onClick,
  buttonProps,
  IconComponent,
  variant,
  ...IconProps
}) => {
  return (
    <Button
      as="button"
      type="button"
      className={className}
      style={style}
      onClick={onClick}
      variant={variant}
      {...buttonProps}
    >
      <StyledIcon as={IconComponent} {...IconProps} />
      {children}
    </Button>
  );
};

IconButton.defaultProps = defaultProps;
