import React, { Component } from 'react';
import {
  Image,
  StyleSheet,
  Text,
  TouchableNativeFeedback,
  View,
} from 'react-native';
import { Icon } from 'react-native-elements';
import ImagePicker from 'react-native-image-picker';

interface Props {
  photoUrl?: string;
  editable?: boolean;
  onNewPath?: (path: string) => void;
}

interface State {
  source: Source;
  history: Array<Source>;
}

interface Source {
  path?: string;
  uri: string;
}

export class PhotoArea extends Component<Props, State> {

  constructor(props: Props) {
    super(props);
    this.state = {
      source: { uri: props.photoUrl },
      history: [],
    };
  }

  componentWillReceiveProps(nextProps: Props) {
    if (nextProps.photoUrl !== this.props.photoUrl) {
      this.setState({
        history: [...this.state.history, this.state.source],
      });
      this.setState({ source: { uri: nextProps.photoUrl }});
    }
  }

  setSourceFromPath = (path) => {
    this.setState({ source: { uri: `file://${path}`, path } });
  }

  goBack = () => {
    const source = this.state.history[this.state.history.length - 1];
    const history = this.state.history.slice(0, -1);
    this.setState({
      history,
      source,
    });
    console.log('goBack');
    console.log(source);
    this.props.onNewPath(source.path || source.uri);
  }

  chooseImage = () => ImagePicker.showImagePicker({ noData: true, maxWidth: 500, maxHeight: 500 }, (response) => {
    console.log(' Image picker response = ', response);
    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      this.setState({
        history: [
          ...this.state.history, this.state.source,
        ],
      });
      this.setSourceFromPath(response.path);
      this.props.onNewPath(response.path);
    }
  })

  renderButton() {
    return this.state.history.length === 0 && !this.props.photoUrl ?
      (
        <View style={{ alignItems: 'center' }}>
          <TouchableNativeFeedback onPress={this.chooseImage}>
            <View style={{ padding: 6 }}>
              <Icon name={'add-a-photo'} size={26} color={'gray'} />
              <Text style={{ margin: 3 }}>Wybierz zdjęcie</Text>
            </View>
          </TouchableNativeFeedback>
        </View>
      )
      : (
        <View style={styles.buttonRow}>
          <TouchableNativeFeedback onPress={this.chooseImage}>
            <Text style={styles.buttonText}>Zmień</Text>
          </TouchableNativeFeedback>
          {
            this.state.history.length > 0 && (
              <TouchableNativeFeedback onPress={this.goBack}>
                <Text style={styles.buttonText}>Cofnij</Text>
              </TouchableNativeFeedback>
            )
          }
        </View>
      );
  }

  render() {
    return (
      <View>
        {this.props.editable && (
          <Text style={{ fontWeight: 'bold', padding: 12 }}>
            Zdjęcie
          </Text>
        )}
        <Image
          style={{ height: 250 }}
          resizeMode='cover'
          source={this.state.source}
        />
        {this.props.editable && this.renderButton()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  buttonRow: {
    height: 40,
    marginTop: -40,
    backgroundColor: 'rgba(255,255,255, 0.7)',
    flexDirection: 'row',
    flex: 1,
    marginVertical: 6,
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  buttonText: {
    fontWeight: 'bold',
    color: 'gray',
  },
  toggle: {
    height: 36,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
