// @flow
/* eslint-disable jsx-a11y/mouse-events-have-key-events */
import React from 'react';
import { StyleSheet, View } from 'react-native';
import Typography from '../Typography/Typography';
import Ripple from '../Utils/Ripple';
import Elevation from '../Elevation/Elevation';
import { border, colors } from '../Utils/Theme';
import styles from './Button.styles';

const { radius: BORDER_RADIUS } = border;

type Props = {
  color?: string,
  compact: boolean,
  dense: boolean,
  href: ?string,
  onPress: (event: Event) => void,
  primary: boolean,
  raised: boolean,
  secondary: boolean,
  target: ?string,
  title: string,
};

type State = {
  isPressed: boolean,
};

class Button extends React.Component<Props, State> {
  static defaultProps = {
    compact: false,
    dense: false,
    href: null,
    primary: false,
    secondary: false,
    onPress: () => {},
    raised: false,
    style: {},
    target: null,
    title: '',
  }

  state = {
    isPressed: false,
  }

  getColor = () => {
    const { color, primary, secondary } = this.props;
    if (primary) {
      return colors.primary;
    }
    if (secondary) {
      return colors.secondary;
    }
    return color;
  }

  setPressed = () => { this.setState({ isPressed: true }); }
  removePressed = () => { this.setState({ isPressed: false }); }

  hasBackground = () => {
    const { color, primary, secondary, raised } = this.props;
    return (primary || secondary || color) && raised;
  }

  render() {
    const { compact, dense, href, onPress, raised, target, title } = this.props;
    const { isPressed } = this.state;
    const hasBackground = this.hasBackground();
    const textColor = hasBackground ? 'rgb(255, 255, 255)' : this.getColor();
    let level = isPressed ? 8 : 2;
    if (!raised) {
      level = 0;
    }

    const buttonStyles = StyleSheet.flatten([
      styles.button,
      hasBackground && { backgroundColor: this.getColor() },
    ]);
    const layoutStyles = StyleSheet.flatten([
      styles.normal,
      compact && styles.compact,
      dense && styles.dense,
    ]);

    return (
      <Elevation level={level} borderRadius={BORDER_RADIUS}>
        <View style={buttonStyles}>
          <Ripple
            {...(hasBackground ? {} : { color: this.getColor() })}
            onPress={onPress}
            onPressIn={this.setPressed}
            onPressOut={this.removePressed}
          >
            <View
              style={layoutStyles}
              accessibilityRole={href ? 'link' : 'button'}
              href={href}
              target={target}
            >
              <Typography type="button" text={title} color={textColor} />
            </View>
          </Ripple>
        </View>
      </Elevation>
    );
  }
}

export default Button;
