import React, {Component} from "react";
import { ScrollView, StyleSheet, ImageBackground, TouchableHighlight, TouchableWithoutFeedback, Dimensions, Image, View, Modal, ActionSheetIOS, Picker, Platform, TouchableOpacity} from "react-native";
// Add Text and Image
import styles from "./style";
import { connect } from 'react-redux';
import { increment, increment_other } from '../../actions';
import { AsyncStorage } from "react-native";

//import { products } from './products';
//import { Product } from './Product';
import products  from '../Activity/products';
import friends  from '../Activity/friends';
import { Button, Block, Text, Input, theme } from 'galio-framework';

const { width } = Dimensions.get('screen');
const thumbMeasure = (width - 48 - 32) / 3;

class Product extends React.Component {
  state = {
      'matchScore': null //This is what our data will eventually be loaded into
  };

  /*
  retrieveData = async () => {
      try {
        const rawValue = await AsyncStorage.getItem('personalPreferences');
        const parsedValue = JSON.parse(rawValue);
        return parsedValue;
      } catch (error) {
          console.log("Error retrieving")
      }
      return value
  };*/

    componentDidMount() {
        this.loadData();
    }

    computeMatchScore() {
      const { navigation, product, preferences, horizontal, full, style, priceColor, imageStyle } = this.props;
      var score = 80 + 20 * (this.cosinesim(product.values, preferences));
      return score;
    }

    // from https://stackoverflow.com/questions/51362252/javascript-cosine-similarity-function
    cosinesim(A,B) {
      var dotproduct=0;
      var mA=0;
      var mB=0;
      for(i = 0; i < A.length; i++){ 
          dotproduct += (A[i] * B[i]);
          mA += (A[i]*A[i]);
          mB += (B[i]*B[i]);
      }
      mA = Math.sqrt(mA);
      mB = Math.sqrt(mB);
      var similarity = (dotproduct)/((mA)*(mB)) 
      var similarity = similarity.toFixed(1);
      return similarity;
    }

    loadData() {
      console.log("I'm coming up with match score now: ")
      var matchScore = this.computeMatchScore()
      console.log(matchScore)
      this.setState({
        'matchScore': matchScore
      });
  }

  render() {
    if (!this.state.matchScore) {
      return null
    }
    var friendImages =   [
        require('../Activity/FriendPics/lexi-pic.jpeg'),
        require('../Activity/FriendPics/greg-pic.jpeg'),
        require('../Activity/FriendPics/jessica-pic.jpeg'),
        require('../Activity/FriendPics/soraya-pic.jpeg'),
        require('../Activity/FriendPics/jennifer-pic.jpeg'),
        require('../Activity/FriendPics/reid-pic.jpeg'),
        require('../Activity/FriendPics/grant-pic.jpeg'),
        require('../Activity/FriendPics/liz-pic.jpeg'),
        require('../Activity/FriendPics/kristen-pic.jpeg'),
        require('../Activity/FriendPics/samuel-pic.jpeg'),
      ];
    const { navigation, product, horizontal, full, style, priceColor, imageStyle, index } = this.props;
    const imageStyles = styles2.image
    var numExtraFriends = products[index].numFriends - 3

    return (
      <Block row={horizontal} card flex style={[styles2.product, styles2.shadow, style]}>
      <View>
          <Block flex style={[styles2.imageContainer, styles2.shadow]}>
            <Image source={{ uri: product.image }} style={imageStyles} />
          </Block>

          <View
          style={{
            flexDirection: 'row',
            marginLeft: 10,
          }}
        >
            <View style={styles2.questionContainer}>
              <Text style={styles2.questionTextContainer}>?</Text>
          </View>
          <View style={styles2.friendContainer}>
          <Image
               style={styles2.circleImage}
               source={friendImages[products[index].friendIndices[0]]}
             />
          </View>
          <View style={styles2.friendContainer}>
          <Image
               style={styles2.circleImage}
               source={friendImages[products[index].friendIndices[1]]}
             />
          </View>
          <View style={styles2.friendContainer}>
          <Image
               style={styles2.circleImage}
               source={friendImages[products[index].friendIndices[2]]}
             />
          </View>
          <View style={styles2.moreFriendsContainer}>
              <Text style={styles2.moreFriendsTextContainer}>+{numExtraFriends}</Text>
          </View>
          </View>
    </View>

          <Block flex space="between" style={styles2.productDescription}>
            <Text size={26} style={styles2.productTitle}>{product.title}</Text>
            <Text style={styles2.matchText}>{this.state.matchScore}% match</Text>

            <Text style = {styles2.distanceText}>{product.distance} away</Text>
          </Block>
      </Block>
    );
  }
}

//export default withNavigation(Product);

const styles2 = StyleSheet.create({
  product: {
    backgroundColor: '#F2F5F7',
    marginVertical: theme.SIZES.BASE,
    borderWidth: 0,
    width: Dimensions.get('window').width - 36,
    minHeight: 160,
  },
  productTitle: {
    color   :'#3F6072',
    fontWeight:'bold',
    textAlign: "center",
  },
  distanceText: {
    color   :'#3F6072',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 16,
  },
  matchText: {
    color:'#3F6072',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 22,
  },
  productDescription: {
    padding: theme.SIZES.BASE / 2,
  },
  imageContainer: {
    elevation: 1,
  },
  image: {
    borderRadius: 6,
    marginHorizontal: theme.SIZES.BASE / 2,
    marginTop: 5,
    height: 115,
    width: 185,
    marginBottom: 7,
  },
  shadow: {
    shadowColor: theme.COLORS.BLACK,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 4,
    shadowOpacity: 0.1,
    elevation: 2,
  },
  circleImage:{
    height: 30,
    width:30,
    borderRadius:500
  },
  friendContainer: {
    marginLeft: 5,
    marginBottom: 2,
  },
  moreFriendsContainer:{
  marginLeft: 5,
  backgroundColor: "#3F6072", 
  justifyContent: "center",
  height: 30,
  width: 30,
  borderRadius: 500,
},
moreFriendsTextContainer: {
  textAlign: "center",
  fontSize: 14,
  overflow: "hidden", 
  color: "#FFFFFF",
},
questionContainer:{
  marginRight: 15,
  backgroundColor: "#F2F5F7", 
  justifyContent: "center",
  height: 30,
  width: 30,
  borderWidth: 3,
  borderRadius: 500,
  borderColor: '#3F6072',
},
questionTextContainer: {
  textAlign: "center",
  fontSize: 14,
  overflow: "hidden", 
  color: "#3F6072",
},
});

class Home extends Component {
  static navigationOptions = {
    headerShown: false,
    isPopupVisible: false,
    /*headerStyle: {
      backgroundColor: '#90CCF4',
      borderBottomWidth: 1,
    },*/
  };
  
  constructor(props) {
    super(props);
    this.state = {
      indexes: null,
      preferences: this.props.navigation.getParam("prefArrayParam"),
      isPopupVisible: false,
    };
    this.renderCards = this.renderCards.bind(this);
    this.loadData = this.loadData.bind(this);
    this.handleClick = this.handleClick.bind(this);
    console.log("On Home Screen")
    console.log(this.state.preferences)
  }

  componentWillMount(){
    AsyncStorage.clear();
  }

  componentDidMount() {
    this.loadData();
  }

  handleClick(){
    window.displayNum = 2
    this.props.navigation.navigate('ThingToDo')
  }

/*
  storeData = async () => {
    try {
      await AsyncStorage.setItem('personalPreferences', JSON.stringify([0, 0, 40, 0, 0]));
    } catch (error) {
      console.log("Error storing")
    }
  };*/

  retrieveData = async () => {
    try {
      const rawValue = await AsyncStorage.getItem('personalPreferences');
      const parsedValue = JSON.parse(rawValue);
      console.log("Parsed Value:")
      console.log(parsedValue)
      return parsedValue;
    } catch (error) {
        console.log("Error retrieving")
    }
    return value
  };

  cosinesim(A,B) {
    var dotproduct=0;
    var mA=0;
    var mB=0;
    for(i = 0; i < A.length; i++){ 
        dotproduct += (A[i] * B[i]);
        mA += (A[i]*A[i]);
        mB += (B[i]*B[i]);
    }
    mA = Math.sqrt(mA);
    mB = Math.sqrt(mB);
    var similarity = (dotproduct)/((mA)*(mB)) 
    var similarity = similarity.toFixed(1);
    return similarity;
  }

  loadData() {
    //this.storeData()
   // this.retrieveData().then(() => {
      console.log("Loading")
      preferences = this.state.preferences
      var computedScores = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      var i;
      var weightSum = 0;
      var threeIndexes = [];
      for (ll = 0; ll < 5; ll++){
        weightSum += preferences[ll]
      }
      for (var i = 0; i < 10; i++) {
        computedScores[i] = this.cosinesim(products[i].values, preferences)
      }
      sortedScores = [...computedScores]
      sortedScores.sort()
      sortedScores.reverse()
      var prevLargestVal = -1;
      dance:
      for (var j = 0; j < 3; j++){
        largestValue = sortedScores[j];
        var k = -1;
        while (((k = computedScores.indexOf(largestValue, k+1)) != -1) && prevLargestVal != largestValue){
            threeIndexes.push(k); 
            if (threeIndexes.length >= 3){
              break dance;
            }
        }
        prevLargestVal = largestValue
      }
      console.log("Test")
      console.log(threeIndexes)
      console.log(preferences)
      this.setState({
        'indexes': threeIndexes,
      //  'preferences': preferences
      }); //    }).catch((error) => {
 //     console.log('Profile: Promise is rejected with error: ' + error);
  //  }); 
  }
  getModal(visible, isPopupVisible){
    if (isPopupVisible) {
      this.setState({ isPopupVisible: visible });
    }
  }

  renderCards(){
    console.log("Is modal visible:")
    console.log(this.state.isPopupVisible)
    return (
      <Block flex style={styles.group}>
        <View style={styles.backgroundModal}>
          <Modal animationType = {"fade"} transparent = {true}
            visible = {this.state.isPopupVisible}>
            <View style = {styles.modalContainer}>
              <Text style={styles.modalText}>
              Why was this option picked?
              </Text>
              <Text style={styles.modalBody}>
               I find the best activities that fit your schedule and your interests that are all within a half mile from your current location! I chose this option because I learned from your survey and social media that you value:
              </Text>
              <TouchableHighlight style={styles.modalExit} onPress = {() => {
                this.getModal(!this.state.isPopupVisible, true)}}>
                <Text style={styles.modalExitText}>X</Text>
              </TouchableHighlight>
            </View>
          </Modal>
        </View>
        <TouchableOpacity style={styles.settingButton} onPress={() => { this.props.navigation.navigate("MainSettings") }}>
           <Image source={require('../Activity/FriendPics/gear.png')} style={styles.settingObject}/>
         </TouchableOpacity>
        <View style={styles.textContainer}>
          <Text bold size={16} style={styles.title}>Your Top 3 Picks</Text>
        </View>
        <Block flex>
          <Block style={{ paddingHorizontal: theme.SIZES.BASE }}>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes[0]})}>
              <Product product={products[this.state.indexes[0]]} preferences = {this.state.preferences} index={this.state.indexes[0]} horizontal />
            </TouchableOpacity>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity',{prefArrayParam: this.state.preferences, indexParam: this.state.indexes[1]})}>
              <Product product={products[this.state.indexes[1]]} preferences = {this.state.preferences} index={this.state.indexes[1]} horizontal />
            </TouchableOpacity>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes[2]})}>
              <Product product={products[this.state.indexes[2]]} preferences = {this.state.preferences} index={this.state.indexes[2]} horizontal />
            </TouchableOpacity>
          </Block>
        </Block>
          <View style={styles.chatBotContainer}>
            <Text style={styles.chatBotTextContainer}>Don't like your options? Tell me what you want!</Text>
        </View>
          <TouchableOpacity style={styles.globeContainer} onPress={() => { this.props.navigation.navigate("Home") }}>
           <Image source={require('../globe.png')} style={styles.globePosition}/>
         </TouchableOpacity>
          <TouchableOpacity style={styles.startChattingContainer} onPress={() => this.props.navigation.navigate('Chatbot', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes})}>
            <Text style={styles.startChattingTextContainer}>Start Chatting...</Text>
        </TouchableOpacity>
      </Block>
    )
  }

 /* render() {
    const navigation = this.props.navigation;
    const increment = this.props.increment;
    const increment_other = this.props.increment_other;
    const i = this.props.i;
    const other = this.props.other;

    return (
      <View style={{flex:1, padding: 50}}>
        <Button onPress={() => {increment(); navigation.navigate('NotHome')}} title="You are at home" />
        <Text>i: {i}</Text>
        <Button onPress={() => {increment_other();}} title="Just increment" />
        <Text>other: {other}</Text>
      </View>
    );
  }*/

  render() {
    const navigation = this.props.navigation;
    const increment = this.props.increment;
    const increment_other = this.props.increment_other;
    const i = this.props.i;
    const other = this.props.other;

    if (!this.state.indexes) {
        return null;
    }

    //WE HAVE DATA, DO A NORMAL RENDER
    return (
      <Block flex center>
        <ScrollView
          style={styles.components}
          showsVerticalScrollIndicator={false}>
            {this.renderCards()}
        </ScrollView>
      </Block>
    );
  }
}

const mapStateToProps = (state) => {
    return {
      i: state.i,
      other: state.other,
    };
};
const mapDispatchToProps = (dispatch) => {
    return {
      increment: () => dispatch(increment()),
      increment_other: () => dispatch(increment_other()),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);
