import * as React from 'react';
import { CSSProperties, MouseEvent } from 'react';
import DOMPurify from 'dompurify';
import { classes } from 'typestyle';
import { ARROW_DIMENSIONS } from '../../consts';
import { ArrowSize } from '../../../types';
import LeftArrowIcon from './LeftArrow';
import RightArrowIcon from './RightArrow';

interface ArrowProps {
  direction: 'left' | 'right';
  disabled: boolean;
  onClick: (e: MouseEvent<HTMLButtonElement>) => void;
  show: boolean;
  classPrefix: string | undefined;
  size?: ArrowSize;
  ariaLabel?: string;
  customArrow?: string;
}

const Arrow = ({
  direction,
  disabled,
  onClick,
  show,
  classPrefix,
  size = 'medium',
  ariaLabel,
  customArrow,
}: ArrowProps) => {
  const ArrowIcon = direction === 'left' ? LeftArrowIcon : RightArrowIcon;

  if (!show) {
    return (
      <div
        style={hiddenButton}
        className={classes(`${classPrefix}-arrow`, `${classPrefix}-arrow-${direction}`)}
      />
    );
  }

  const defaultLabel = direction === 'left' ? 'Previous' : 'Next';
  const finalLabel = `${ariaLabel ?? defaultLabel}${disabled ? ' (disabled)' : ''}`;

  return (
    <button
      type='button'
      style={getButtonStyle(size, disabled)}
      className={classes(`${classPrefix}-arrow`, `${classPrefix}-arrow-${direction}`)}
      onClick={onClick}
      disabled={disabled}
      aria-disabled={disabled}
      aria-label={finalLabel}
    >
      {customArrow ? (
        <span aria-hidden='true' dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(customArrow) }} />
      ) : (
        <ArrowIcon enabled={!disabled} size={size} aria-hidden='true' />
      )}
    </button>
  );
};

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

const hiddenButton: CSSProperties = {
  display: 'none',
};

export default Arrow;
