// @flow
/* eslint-disable jsx-a11y/mouse-events-have-key-events */
import React from 'react';
import type { Node } from 'react';
import { StyleSheet, TouchableWithoutFeedback, View } from 'react-native';
import { rgbToRgba } from '../Utils/Utils';

type Props = {
  borderRadius: number,
  children: Node,
  color: string,
  onPress: (event: Event) => void,
  onPressIn: (event: Event) => void,
  onPressOut: (event: Event) => void,
};

type State = {
  isHovered: boolean,
  isPressed: boolean,
};

class Ripple extends React.Component<Props, State> {
  static defaultProps = {
    borderRadius: 0,
    color: 'rgb(33, 33, 33)',
    onPress: () => {},
    onPressIn: () => {},
    onPressOut: () => {},
  }

  state = {
    isHovered: false,
    isPressed: false,
  }

  setHover = () => this.setState({ isHovered: true });
  setPressed = (event: Event) => {
    this.setState({ isPressed: true });
    this.props.onPressIn(event);
  }
  removeHover = () => this.setState({ isHovered: false });
  removePressed = (event: Event) => {
    this.setState({ isPressed: false });
    this.props.onPressOut(event);
  }

  render() {
    const { borderRadius, children, color, onPress } = this.props;
    const { isHovered, isPressed } = this.state;

    const styles = StyleSheet.flatten([
      isHovered && { backgroundColor: rgbToRgba(color, 0.04) },
      isPressed && { backgroundColor: rgbToRgba(color, 0.12) },
      borderRadius && { borderRadius },
    ]);

    return (
      <TouchableWithoutFeedback
        onMouseOver={this.setHover}
        onMouseOut={this.removeHover}
        onPress={onPress}
        onPressIn={this.setPressed}
        onPressOut={this.removePressed}
      >
        <View style={styles}>{children}</View>
      </TouchableWithoutFeedback>
    );
  }
}

export default Ripple;
