import React, {Component} from "react";
import {Image, View,ScrollView, Modal, TextInput, TouchableHighlight, TouchableWithoutFeedback, Slider, ActionSheetIOS, SafeAreaView, Dimensions, Picker, Text, Platform, TouchableOpacity, Button} from "react-native";
import styles from "./style";
import { connect } from 'react-redux';
import { Card } from 'react-native-elements';
import options from './optionsdata.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import {KeyboardAvoidingView} from 'react-native';
import Stars from 'react-native-stars';
import products  from './products';

// Stars: https://www.npmjs.com/package/react-native-stars
class Feedback extends Component {
	static navigationOptions = {headerShown: false, gesturesEnabled: false};
	constructor(props) {
	super(props);
	this.state = {
		isStarVisible: false,
		isTagVisible:  false,
		//preferencesArray: this.props.navigation.getParam("prefArrayParam"),
		starPressed: false,
		tagsPressed: false,
		tags: ['Clean', 'Calm', 'Cheap', 'Quirky', 'Quick', 'Fun', 'Add Tag:'],
		pressFlags: [false, false, false, false, false, false, false],
		tagText: '',
		fromSettings: this.props.navigation.getParam("fromSettings"),
		preferences: this.props.navigation.getParam("preferences"),
      	activityIndex: this.props.navigation.getParam("activityIndex"),
      	visitedList: this.props.navigation.getParam("visitedList"),
     	avoidList: this.props.navigation.getParam("avoidList"),
     	lastStarReview: 0,
     	calendarSync: this.props.navigation.getParam("calendarSync"),
     	defaultStar: 0,
	};
	this.renderForward = this.renderForward.bind(this);
	this.renderTags = this.renderTags.bind(this);
	this.getOptionButton = this.getOptionButton.bind(this);
	this.getCustomOptionButton = this.getCustomOptionButton.bind(this);
	console.log("Social")
    console.log(this.state.preferencesArray)
}

componentDidMount(){
	if (this.props.navigation.getParam("lastReview") !== undefined)
	{
		this.setState({starPressed: true, lastStarReview: this.props.navigation.getParam("lastReview"), defaultStar: this.props.navigation.getParam("lastReview")})
	}
}
getModal(visible, isFB){
	if (isFB) {
		this.setState({ isFBVisible: visible });
	} else {
		this.setState({ isGCVisible: visible });
	}
}

getLocModal(visible){
	this.setState({ isLocVisible: visible });
}

activateStars(val){
	visitList = this.state.visitedList
	lastElem = visitList.pop()
	lastElem[this.state.activityIndex] = val
	visitList.push(lastElem)
	this.setState({stars: val, starPressed: true, visitedList: visitList, lastStarReview: val})

	console.log(val)
	// Pass logic to backend about star rating
}


renderForward(){
	const screenWidth = Dimensions.get('window').width;
	if (this.state.starPressed === true){
		return (
			<TouchableOpacity style={this.state.isStarVisible ? styles.greyNextReviewButton : styles.nextReviewButton} onPress={() => { this.scroll.scrollTo({ x: screenWidth * 2 }) }}>
			   <Image source={require('./right.png')} style={styles.nextReviewObject}/>
			</TouchableOpacity>
		);
	} else {
		return (
			<View style={styles.hiddenButton}>
			</View>
		);
	}
}

renderTagsForward(){
	const screenWidth = Dimensions.get('window').width;
	tagsPressed = false
	for (let i = 0; i < this.state.pressFlags.length; i++){
		let flag = this.state.pressFlags[i];
		if (flag === true){
			tagsPressed = true;
			break;
		}
	}
	if (tagsPressed === true){
		return (
			<TouchableOpacity style={this.state.isTagVisible ? styles.greyNextReviewButton : styles.nextReviewButton} onPress={() => { this.props.navigation.navigate('FeedbackOutro', {fromSettings: false, preferences: this.state.preferences, calendarSync: this.state.calendarSync, activityIndex: this.state.activityIndex, visitedList: this.state.visitedList, avoidList: this.state.avoidList}/* Need to add preferences array or crash*/) }}>
			   <Image source={require('./right.png')} style={styles.nextReviewObject}/>
			</TouchableOpacity>
		);
	} else {
		return (
			<View style={styles.hiddenButton}>
			</View>
		);
	}
}

activateButton(pressFlag, keyValue){
	prevArray = this.state.pressFlags
	if (prevArray[keyValue] === true){
		prevArray[keyValue] = false
		this.setState({ pressFlags: prevArray })
	} else {
		prevArray[keyValue] = true
		this.setState({ pressFlags: prevArray })
	}
}

getOptionButton(optionText, pressFlag, keyValue){
	if (pressFlag === true){
		return (
			<TouchableOpacity
				key={keyValue}
				style={this.state.isTagVisible ? styles.greyPressedTagButton : styles.pressedTagButton}
				activeOpacity={.8}
				onPress={() => this.activateButton(pressFlag, keyValue)}
				>
				<Text style={this.state.isTagVisible ? styles.greyTagText : styles.tagText}>
					{optionText}
				</Text>

			</TouchableOpacity>
		);
	} else {
		return (
			<TouchableOpacity
				key={keyValue}
				style={this.state.isTagVisible ? styles.greyTagButton : styles.tagButton}
				activeOpacity={.8}
				onPress={() => this.activateButton(pressFlag, keyValue)}
				>
				<Text style={this.state.isTagVisible ? styles.greyTagText : styles.tagText}>
					{optionText}
				</Text>
			</TouchableOpacity>
		);
	}
}

activateCustomButton(keyValue){
	prevArray = this.state.pressFlags
	if (this.state.tagText.length > 0){
		prevArray[keyValue] = true
		this.setState({ pressFlags: prevArray })
	} else {
		prevArray[keyValue] = false
		this.setState({ pressFlags: prevArray })
	}
}

// OnFocus https://stackoverflow.com/questions/54707607/how-to-setup-onpress-on-textinput-in-react-native
getCustomOptionButton(optionText, keyValue){
	return (
		<View
			key={keyValue}
			style={this.state.isTagVisible ? styles.greyCustomTagButton : styles.customTagButton}
			activeOpacity={.8}
			>
			<Text style={this.state.isTagVisible ? styles.greyCustomTagText : styles.customTagText}>
				{optionText}
			</Text>
			<TextInput
                style={
                  {
                  	position: 'absolute',
                  	width: Dimensions.get('window').width - 36,
                  	paddingTop: 20,
                    paddingLeft: 8,
                    paddingBottom: 2,
                    bottom: 3,
                    fontSize: 16,
                    fontFamily: 'Arial',
                    fontStyle: 'normal',
                    fontWeight: 'normal',
                  }
                }
                placeholder= 'e.g. Nostalgic'
                keyboardType="email-address"
                returnKeyType="done"
                onEndEditing={() => this.activateCustomButton(keyValue)}
                onChangeText={(text) => this.setState({tagText: text})}
                value={this.state.tagText}
             />
		</View>
	);
}

renderTags(){
	let optionList = []
	for (let i = 0; i < this.state.tags.length; i++){
		let option = this.state.tags[i];
		let keyValue = i;
		if (i === 6){
			optionList[i] = this.getCustomOptionButton(option, keyValue);
			console.log(optionList[i])
		} else {
			optionList[i] = this.getOptionButton(option, this.state.pressFlags[keyValue], keyValue);
		}
	}
	return optionList;
}

renderBackwardAction(){
	if (this.state.fromSettings === true){
		return (
			<TouchableOpacity style={styles.topButtonStyle} onPress={() => this.props.navigation.goBack()}>
          		<Image source={require('../thinArrow.png')} style={styles.topArrowStyle}/>
        	</TouchableOpacity>
		);
	} else {
		return;
	}
}

undoLocationConfirm(){
	visitList = this.state.visitedList
	visitList.pop()
	this.setState({visitedList: visitList})
	this.scroll.scrollTo({ x: 0})
}

confirmVisit(screenWidth){
	visitList = this.state.visitedList
	activityObj = {}
	activityObj[this.state.activityIndex] = this.state.lastStarReview
	visitList.push(activityObj)
	this.setState({visitedList: visitList})
	this.scroll.scrollTo({ x: screenWidth, animated: true })
}

skipAtReview(){
	visitList = this.state.visitedList
	lastElem = visitList.pop()
	lastElem[this.state.activityIndex] = 0
	visitList.push(lastElem)
	this.props.navigation.navigate('FeedbackOutro', {fromSettings: false, preferences: this.state.preferences, calendarSync: this.state.calendarSync, activityIndex: this.state.activityIndex, visitedList: visitList, avoidList: this.state.avoidList}/* Need to add preferences array or crash*/)
}

render() {
	const navigation = this.props.navigation;
	const screenWidth = Dimensions.get('window').width;
	//https://www.tutorialspoint.com/react_native/react_native_modal.htm
	//https://github.com/ReactNativeSchool/react-native-quiz/blob/master/App/data/computers.js
	//https://stackoverflow.com/questions/51629192/react-native-horizontal-scroll-on-button-click
	return (
		<ScrollView horizontal={true} scrollEnabled={false} pagingEnabled={true} decelerationRate={'fast'} showsHorizontalScrollIndicator={false} ref={(node) => this.scroll = node}>
			<View style={{flex: 1, alignItems: 'center', width: Dimensions.get('window').width}}>
				{this.renderBackwardAction()}
				<Text style={styles.headerText}>
					Did you go to {products[this.state.activityIndex].title}?
				</Text>
				<Image source={{uri: products[this.state.activityIndex].image }} style={styles.locationPicture}>
				</Image>
				<View style={styles.locationConfirmContainer}>
					<TouchableOpacity
						style={styles.noButton}
						activeOpacity={.8}
						onPress={() => { this.props.navigation.navigate('FeedbackOutro', {fromSettings: this.state.fromSettings, noVisit: true, preferences: this.state.preferences, calendarSync: this.state.calendarSync, activityIndex: this.state.activityIndex, visitedList: this.state.visitedList, avoidList: this.state.avoidList}/* Need to add preferences array or crash*/)}}>
						<Text style={styles.locationConfirmButtonText}>
							No
						</Text>
					</TouchableOpacity>
					<TouchableOpacity
						style={styles.yesButton}
						activeOpacity={.8}
						onPress={() => this.confirmVisit(screenWidth)}>
						<Text style={styles.locationConfirmButtonText}>
							Yes
						</Text>
					</TouchableOpacity>
				</View>
			</View>
			<View style={this.state.isStarVisible ? {backgroundColor: 'rgba(0,0,0,0.5)', flex: 1, alignItems: 'center', width: Dimensions.get('window').width} : {flex: 1, alignItems: 'center', width: Dimensions.get('window').width}}>
				<Text style={this.state.isStarVisible ? styles.greyHeaderText : styles.headerText}>
					What did you think of {products[this.state.activityIndex].title}?
				</Text>
				<Image source={{uri: products[this.state.activityIndex].image }} style={styles.locationPicture}>
				</Image>
				<TouchableOpacity style={styles.popTextContainer} onPress={() => this.setState({ isStarVisible: true })}>
					<Text style={styles.helpPopText}>
						Why do this?
					</Text>
				</TouchableOpacity>
				<View style={styles.starContainer}>
				  <Stars
				    default={this.state.defaultStar}
				    update={(val)=>{this.activateStars(val)}}
				    spacing={10}
				    count={5}
				    fullStar={<Image source={require('../star.png')} style={this.state.isStarVisible ? styles.greyFullStar : styles.fullStar}/>}
				    emptyStar={<Image source={require('../star.png')} style={this.state.isStarVisible ? styles.greyEmptyStar : styles.emptyStar}/>}
				   />
				</View>
				<View style={styles.bottomBarContainer}>
					<TouchableOpacity style={this.state.isStarVisible ? styles.greyPrevReviewButton : styles.prevReviewButton} onPress={() => { this.undoLocationConfirm() }}>
					   <Image source={require('./left.png')} style={styles.prevReviewObject}/>
					 </TouchableOpacity>
					
					<TouchableOpacity style={this.state.isStarVisible ? styles.greyLaterReviewButton : styles.laterReviewButton} onPress={() => {this.skipAtReview()}}>
						<Text style={this.state.isStarVisible ? styles.greyLocationConfirmButtonText : styles.locationConfirmButtonText}>
							Later
						</Text>
					</TouchableOpacity>
					{this.renderForward()}
				</View>
				<Modal animationType = {"fade"} transparent = {true}
					visible = {this.state.isStarVisible}>
					<View style = {styles.modalContainer}>
						<Text style={styles.modalText}>
							Why do we ask for ratings?
						</Text>
						<Text style={styles.modalBody}>
							We ask for your ratings after each experience so that we can learn from your experiences. We'll use this information to make better recommendations in the future. 
						</Text>
						<TouchableHighlight style={styles.modalExit} onPress = {() => this.setState({ isStarVisible: false })}>
							<Text style={styles.modalExitText}>X</Text>
						</TouchableHighlight>
					</View>
				</Modal>
			</View>

			<KeyboardAvoidingView style={this.state.isTagVisible ? {backgroundColor: 'rgba(0,0,0,0.5)'} : ''}behavior='position' enabled>
				<View style={{flex: 1, alignItems: 'center', width: Dimensions.get('window').width}}>
					<Text style={this.state.isTagVisible ? styles.greyHeaderText : styles.headerText}>
						Which tags accurately describe your experience?
					</Text>
					<Image source={{uri: products[this.state.activityIndex].image }} style={styles.locationPicture}>
					</Image>
					<TouchableOpacity style={styles.popTextContainer} onPress={() => this.setState({ isTagVisible: true })}>
						<Text style={styles.helpPopText}>
							Why do this?
						</Text>
					</TouchableOpacity>
					<View style={styles.tagContainer}>
						{this.renderTags()}
					</View>

					<View style={styles.bottomBarContainer}>
						<TouchableOpacity style={this.state.isTagVisible ? styles.greyPrevReviewButton : styles.prevReviewButton} onPress={() => { this.scroll.scrollTo({ x: screenWidth}) }}>
						   <Image source={require('./left.png')} style={styles.prevReviewObject}/>
						 </TouchableOpacity>
						
						<TouchableOpacity style={this.state.isTagVisible ? styles.greyLaterReviewButton : styles.laterReviewButton} onPress={() => { this.props.navigation.navigate('FeedbackOutro', {fromSettings: false, preferences: this.state.preferences, calendarSync: this.state.calendarSync, activityIndex: this.state.activityIndex, visitedList: this.state.visitedList, avoidList: this.state.avoidList}/* Need to add preferences array or crash*/)}}>
							<Text style={this.state.isTagVisible ? styles.greyLocationConfirmButtonText : styles.locationConfirmButtonText}>
								Later
							</Text>
						</TouchableOpacity>
						{this.renderTagsForward()}
					</View>
					<Modal animationType = {"fade"} transparent = {true}
						visible = {this.state.isTagVisible}>
						<View style = {styles.modalContainer}>
							<Text style={styles.modalText}>
								Why do we ask you to select tags?
							</Text>
							<Text style={styles.modalBody}>
								We want to learn more about what you thought about an experience. This helps us improve recommendations in the future and help your friends learn more about what an experience is like.
							</Text>
							<TouchableHighlight style={styles.modalExit} onPress = {() => this.setState({ isTagVisible: false })}>
								<Text style={styles.modalExitText}>X</Text>
							</TouchableHighlight>
						</View>
					</Modal>
				</View>
			</KeyboardAvoidingView>
		</ScrollView>
		);
	}
}

export default Feedback;
