import * as React from 'react';
import { CSSProperties, MouseEvent } from 'react';
import DOMPurify from 'dompurify';
import { ARROW_DIMENSIONS } from '../../consts';
import { ArrowSize } from '../../../types';
import AddToCartIcon from '.';

interface AddToCartButtonProps {
  onClick: (e: MouseEvent<HTMLButtonElement>) => void;
  size?: ArrowSize;
  disabled?: boolean;
  ariaLabel?: string;
  classPrefix?: string;
  customIcon?: string;
}

const AddToCartButton = ({
  onClick,
  size = 'medium',
  disabled = false,
  ariaLabel = 'Add to cart',
  classPrefix,
  customIcon,
}: AddToCartButtonProps) => (
  <button
    type='button'
    style={getButtonStyle(size, disabled)}
    className={classPrefix ? `${classPrefix}-add-to-cart` : undefined}
    onClick={onClick}
    disabled={disabled}
    aria-label={ariaLabel}
  >
    {customIcon ? (
      <span aria-hidden='true' dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(customIcon) }} />
    ) : (
      <AddToCartIcon enabled={!disabled} size={size} aria-hidden='true' />
    )}
  </button>
);

const getButtonStyle = (size: ArrowSize, disabled: boolean): CSSProperties => ({
  flexShrink: 0,
  height: '100%',
  padding: ARROW_DIMENSIONS[size].padding,
  backgroundColor: 'transparent',
  border: 'none',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  cursor: disabled ? 'default' : 'pointer',
});

export default AddToCartButton;
