// @flow
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
import TextFieldLabel from './TextFieldLabel';
import styles from './TextField.styles';

type State = {
  hasValue: boolean,
  isFocused: boolean,
  isHovered: boolean,
};

type Props = {
  defaultValue?: string,
  label: string,
  onBlur: (e: Event) => void,
  onChangeText: (text: string) => void,
  onFocus: (e: Event) => void,
  value?: string,
};

class TextField extends React.Component<Props, State> {
  static defaultProps = {
    label: '',
    onBlur: () => {},
    onChangeText: () => {},
    onFocus: () => {},
  }

  state = {
    hasValue: false,
    isFocused: false,
    isHovered: false,
  }

  componentDidMount() {
    if (this.props.defaultValue || this.props.value) {
      this.setState({ hasValue: true });
    }
  }

  setHover = () => this.setState({ isHovered: true })
  removeHover = () => this.setState({ isHovered: false })

  handleChangeText = (text: string) => {
    this.setState({ hasValue: !!text });
    this.props.onChangeText(text);
  }

  handleBlur = (e: Event) => {
    this.setState({ isFocused: false });
    this.props.onBlur(e);
  }

  handleFocus = (e: Event) => {
    this.setState({ isFocused: true });
    this.props.onFocus(e);
  }


  render() {
    const { label } = this.props;
    const { hasValue, isFocused, isHovered } = this.state;
    const fieldStyles = StyleSheet.flatten([styles.field]);
    const inputStyles = StyleSheet.flatten([
      styles.input,
      isHovered && styles.hovered,
      isFocused && styles.focused,
    ]);

    return (
      <View style={fieldStyles}>
        <TextInput
          onBlur={this.handleBlur}
          onChangeText={this.handleChangeText}
          onFocus={this.handleFocus}
          onMouseOver={this.setHover}
          onMouseOut={this.removeHover}
          style={inputStyles}
        />
        <TextFieldLabel isFocused={isFocused} isRaised={isFocused || hasValue} text={label} />
      </View>
    );
  }
}

export default TextField;
