/* @flow */
import React, { PureComponent } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';

import type { Context, LocalizableText } from '../types';
import Input from './Input';
import { BRAND_COLOR } from '../styles';
import Icon from '../common/Icons';
import Touchable from '../common/Touchable';

const componentStyles = StyleSheet.create({
  clearButtonContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 22,
    height: 22,
    marginRight: 12,
  },
  clearButtonIcon: {
    color: BRAND_COLOR,
  },
});

type Props = {
  placeholder: LocalizableText,
  onChangeText: (text: string) => void,
};

type State = {
  canBeCleared: boolean,
  text: string,
};

/**
 * A component wrapping Input and providing an 'X' button
 * to clear the entered text.
 *
 * @prop [placeholder] - Text to be shown when no value is entered.
 * @prop onChangeText - Event called when text is edited.
 */
export default class InputWithClearButton extends PureComponent<Props, State> {
  context: Context;
  props: Props;
  state: State = {
    canBeCleared: false,
    text: '',
  };
  textInput: TextInput;

  static contextTypes = {
    styles: () => null,
  };

  handleChangeText = (text: string) => {
    this.setState({
      canBeCleared: text.length > 0,
      text,
    });
    this.props.onChangeText(text);
  };

  handleClear = () => {
    this.handleChangeText('');
    this.textInput.clear();
  };

  render() {
    const { styles } = this.context;
    const { canBeCleared, text } = this.state;

    return (
      <View style={styles.row}>
        <Input
          {...this.props}
          textInputRef={textInput => {
            this.textInput = textInput;
          }}
          onChangeText={this.handleChangeText}
          value={text}
        />
        {canBeCleared && (
          <Touchable style={componentStyles.clearButtonContainer} onPress={this.handleClear}>
            <Icon name="x" size={20} style={componentStyles.clearButtonIcon} />
          </Touchable>
        )}
      </View>
    );
  }
}

@@ -279,53 +279,8 @@
 ns';
-%0Aimport Touchable from '../common/Touchable';
 %0A%0Aco
@@ -338,126 +338,59 @@
 tton
-Container: %7B%0A    alignItems: 'center',%0A    justifyContent: 'center',%0A    width: 22,%0A    height: 22,%0A    marg
+Icon: %7B%0A    color: BRAND_COLOR,%0A    padd
 in
+g
 Right: 1
 2,%0A 
@@ -389,59 +389,9 @@
 t: 1
-2,%0A  %7D,%0A  clearButtonIcon: %7B%0A    color: BRAND_COLOR
+6
 ,%0A  
@@ -1681,62 +1681,67 @@
    %3C
-Touchable style=%7BcomponentStyles.clearButtonContainer%7D
+Icon%0A            name=%22x%22%0A            size=%7B24%7D%0A           
  onP
@@ -1763,17 +1763,16 @@
 leClear%7D
-%3E
 %0A       
@@ -1779,33 +1779,8 @@
     
- %3CIcon name=%22x%22 size=%7B20%7D
  sty
@@ -1815,19 +1815,16 @@
 tonIcon%7D
- /%3E
 %0A       
@@ -1830,19 +1830,9 @@
     
-%3C/Touchable
+/
 %3E%0A  

Make button bigger and more padded.