
import * as React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, ActivityIndicator } from 'react-native';
import { Ionicons, MaterialCommunityIcons, SimpleLineIcons } from '@expo/vector-icons';
import { SliderBox } from "react-native-image-slider-box";
import { Card } from 'react-native-shadow-cards';
import { connect } from 'react-redux';
import Axios from 'axios';
import i18n from 'i18n-js';
import _ from 'lodash';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import * as Device from 'expo-device';
import ActionType from '../redux/globalActionType';
import session from '../function/session';
import Constants from 'expo-constants';
import info from '../app.json';


let version = info.expo.version
let buildNumber = info.expo.android.versionCode

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      data_baner: [],
      images: [],
      balance: "",
      point: "",
      account_number: "",
      my_lat: 0,
      my_long: 0,
      indicator: true
    }
  }

  componentDidMount() {
    this._account();
    this._getPermissions()
    this._renderCarousell()

    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      this.setState({
        indicator: true,
      })
      this._account();
      this._getPermissions()
      this._renderCarousell()

    });
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  _getPermissions = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      Alert.alert('Akses tidak dizinkan!')
    } else if (Platform.OS === 'android' && !Device.isDevice) {

      Alert.alert('Silahkan anda coba di real Device')
    } else {
      this._getCurrentPosisition()
    }
  }
  _getCurrentPosisition = async () => {
    this.setState({
      spinner: true,
    })
    let location = await Location.getCurrentPositionAsync({
      accuracy: Location.Accuracy.Highest
    })

    let latitude = location.coords.latitude;
    let longitude = location.coords.longitude;



    this.setState({
      my_lat: latitude,
      my_long: longitude
    })

    let cordinate = {
      lat: this.state.my_lat,
      long: this.state.my_long,
    }
    this.props.setCordinatProps(cordinate);


    this._getOutletClosest();
  }

  _renderCarousell() {
    Axios.get('https://excelsocrm.ravintoladev.com/cms/v2/list/promotions-carousel').then(respon => {
      const dataCarousell = respon.data.contents;
      let imageLink = []

      for (let i = 0; i < dataCarousell.length; i++) {
        const element = dataCarousell[i];
        imageLink.push(element.title_thumb)
      }
      this.setState({
        images: imageLink
      })
    }).catch(error =>{
      
      const { navigation } = this.props
      let response = error.response.data
      session(response, navigation)
    })
  }

  _account() {
    let params = {
      session_id: this.props.session_id,
    }
    // console.log(params);
    Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_profile', params).then(res => {

      const dataCard = res.data
      let point = dataCard.kaspro_point
      let balance = dataCard.kaspro_balance
      let expire = dataCard.expire_date
      let account_number = dataCard.card_number

      this.setState({
        point: point,
        balance: balance,
        account_number: account_number,
        expire_date: expire,
        indicator: false
      })
    }).catch(error => {
      // console.log("INI ERROR " + error);
      // const { navigation } = this.props
      // let response = error.response.data
      // session(response, navigation)
      // Alert.alert(response.msg);
    })
  }

  _getOutletClosest() {
    let params = {
      session_id: this.props.session_id,
      lat: this.state.my_lat,
      long: this.state.my_long
    }
    // console.log(params);
    Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/outlet/get_closest', params).then(res => {


      let outletId = res.data.data.outlet_id
      let outletName = res.data.data.outlet_name

      let OutletChange = {
        outlet_id: outletId,
        name_outlet: outletName,
      }
      this.props.setChangeOutletProps(OutletChange);
      this.setState({
        indicator: false
      })
    }).catch(error => {
      
      const { navigation } = this.props
      let response_data = error.response.data
      let error_status = error.response.status
      session(response_data,error_status,navigation)
      
    })
  }

  _pickup() {
    this.props.navigation.navigate('Pickup Name', { from: 'home' });
  }

  _delivery() {
    this.props.navigation.navigate('Delivery Address', { from: 'home' });
  }

  _orderNow = () => {
    if (this.props.outlet_id != '' && this.props.name_outlet != '') {
      this.props.setTypePickup(true)
      this.props.navigation.navigate('Home', {
        screen: 'MENU',
        params: { user: 'jaxi' },
      });

    } else {
      Alert.alert('Belum dapat outlet terdekat')
    }

  }


  render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <View style={{ flex: 6 }}>
            <View style={styles.header}>
              {/* <StatusBar barStyle='dark-content' /> */}
              {/* <Text style={styles.titleText}>{i18n.t('register')}</Text> */}
              <View style={{ flex: 1, alignItems: 'flex-end' }}>
                <Text style={styles.titleText}>TODAY PROMOTIONS</Text>
              </View>
              <View style={{ margin: 15, flex: 0.15, alignItems: 'flex-end' }}>
                <TouchableOpacity>
                  <SimpleLineIcons name="bell" size={24} color="white" />
                </TouchableOpacity>
              </View>
            </View>
            <SliderBox
              images={this.state.images}
              autoplay
              circleLoop
              dotColor='black'
              inactiveDotColor='white'
              sliderBoxHeight={300}
              paginationBoxVerticalPadding={20}
              resizeMethod={'resize'}
              resizeMode={'stretch'}
              paginationBoxStyle={{
                position: "absolute",
                bottom: 0,
                padding: 0,
                alignItems: 'center',
                alignSelf: 'center',
                justifyContent: 'center',
                paddingVertical: 10,
              }}
              dotStyle={{
                width: 10,
                height: 10,
                borderRadius: 5,
                marginHorizontal: 0,
                padding: 0,
                margin: 0,
              }}
              ImageComponentStyle={{
                width: '100%',
              }}
              imageLoadingColor='#c7c7c7'
            />
          </View>
          <View style={styles.content}>
            <View style={styles.card}>
              <Card>
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                  {/* <TouchableOpacity style={styles.buttonDelivery} onPress={() => this._delivery()}>
                    <Text style={{ textAlign: 'center', color: '#354175', fontWeight: 'bold' }}>{i18n.t('delivery')}</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.buttonPickup} onPress={() => this._pickup()}>
                    <Text style={{ textAlign: 'center', color: '#fff', fontWeight: 'bold' }}>{i18n.t('pickup')}</Text>
                  </TouchableOpacity> */}
                  <TouchableOpacity style={styles.buttonDelivery} onPress={() => this._delivery()}>
                    <Text style={{ textAlign: 'center', color: '#354175', fontWeight: 'bold',fontFamily:'Gotham-Black' }}>DELIVERY</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.buttonPickup} onPress={() => this._pickup()}>
                    <Text style={{ textAlign: 'center', color: '#fff', fontWeight: 'bold',fontFamily:'Gotham-Black'  }}>PICK UP</Text>
                  </TouchableOpacity>
                </View>
                {/* <Text style={{ textAlign: 'center', fontSize: 12, }}>
                  {i18n.t('orderInfo')}
                </Text> */}
                <Text style={{ textAlign: 'center', fontSize: 12, fontFamily:'Gotham-Black' }}>
                  YOU WILL PICKUP YOUR ORDER AT
                </Text>
                {this.state.indicator == true ? (
                  <ActivityIndicator size="small" color="#c9af6d" />
                ) : (
                    <Text style={{ textAlign: "center", fontSize: 12, top: 5, fontWeight: 'bold' }}>
                      Excelso {this.props.name_outlet}
                    </Text>
                  )}
                {/* <TouchableOpacity style={styles.submitOrder} activeOpacity={.5} onPress={() => this._orderNow()}>
                  <Text style={{ textAlign: 'center', bottom: 5, color: 'white' }}>{i18n.t('orderNow')}</Text>
                </TouchableOpacity> */}
                <TouchableOpacity style={styles.submitOrder} activeOpacity={.5} onPress={() => this._orderNow()}>
                  <Text style={{ textAlign: 'center', bottom: 5, color: 'white' }}>ORDER NOW</Text>
                </TouchableOpacity>
              </Card>
              {
                this.state.indicator == true ? (<ActivityIndicator style={{ top: 20, justifyContent: "center" }} size="large" color="#c9af6d" />) :
                  this.state.account_number === "" ? (
                    <View style={styles.card}>
                      <Card style={{ padding: 10, margin: 10, alignContent: 'center' }}>
                        <Text style={{ textAlign: "center" }}> Anda belum aktivasi kartu</Text>
                        <Text>
                        </Text>
                        <Text style={{ textAlign: "center", fontSize: 40, color: '#c9af6d' }}>

                        </Text>
                        <View style={styles.line}></View>
                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}> {'\n'}

                        </Text>
                        <View style={styles.line}></View>
                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>{'\n'}
                        </Text>
                      </Card>
                    </View>
                  ) :

                    (
                      <View style={styles.card}>
                        <Card style={{ padding: 20, margin: 10, alignContent: 'center' }}>
                          {/* <Text>
                            {i18n.t('yourCardNumber')} | {this.state.expire_date}{'\n'}
                          </Text> */}
                          {/* <Text>
                            YOUR CARD NUMBER | {this.state.expire_date}
                          </Text> */}
                          <View style={{ flexDirection: 'row', flex: 1 }}>
                            <View style={{ flex: 0.5 }}>
                              <Text style={{ fontSize: 9 ,fontFamily:'Gotham-Black'}}>YOUR CARD NUMBER</Text>
                            </View>
                            <View style={{ flex: 0.5 }}>
                              <Text style={{ fontSize: 9, textAlign: 'right',fontFamily:'Gotham-Black' }}>Expired At {this.state.expire_date}</Text>
                            </View>
                          </View>
                          <View style={{ paddingHorizontal: 10 }}>
                            <Text style={{ textAlign: "center", fontSize: 30, color: '#c9af6d',fontFamily:'Gotham-Black' }}>
                              {this.state.account_number}
                            </Text>
                          </View>
                          <View style={styles.line}></View>


                          {/* <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>
                            {i18n.t('balance')} {this.state.balance}
                          </Text> */}

                          <View style={{ flexDirection: 'row', flex: 1 }}>
                            <View style={{ flex: 0.3, justifyContent: 'center' }}>
                              {/* <Text>{i18n.t('balance')}</Text> */}
                              <Text style={{ fontSize: 10 }}>BALANCE</Text>
                            </View>
                            <View style={{ flex: 0.7 }}>
                              <Text style={{ fontSize: 20 }}>IDR. {this.state.balance}</Text>
                            </View>
                          </View>


                          <View style={styles.line2}></View>
                          {/* <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>
                            {i18n.t('point')} {this.state.point}
                          </Text> */}
                          <View style={{ flexDirection: 'row', flex: 1 }}>
                            <View style={{ flex: 0.3, justifyContent: 'center' }}>
                              {/* <Text>{i18n.t('balance')}</Text> */}
                              <Text style={{ fontSize: 10 }}>POINTS</Text>
                            </View>
                            <View style={{ flex: 0.7 }}>
                              <Text style={{ fontSize: 20 }}>IDR. {this.state.point}</Text>
                            </View>
                          </View>
                        </Card>
                      </View>
                    )
              }
              <View style={{ flexDirection: 'row', flex: 1 }}>
                <TouchableOpacity
                  // style={styles.submitUpgradePemium} 
                  activeOpacity={.5} onPress={this.onPress}>
                  <View style={styles.topUseBalance}>
                    <Text style={{ textAlign: 'center', bottom: 5, color: 'white' }}>TOP BALANCE </Text>
                  </View>
                </TouchableOpacity>
                <TouchableOpacity
                  // style={styles.submitUpgradePemium} 
                  activeOpacity={.5} onPress={this.onPress}>
                  <View style={styles.topUseBalance}>
                    <Text style={{ textAlign: 'center', bottom: 5, color: 'white' }}>USE BALANCE </Text>
                  </View>
                </TouchableOpacity>
              </View>
              <View style={{ height: 60 }}></View>
            </View>
          </View>
        </ScrollView>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  header: {
    flex: 0.1,
    flexDirection: 'row',
    backgroundColor: '#CFB368',
    // justifyContent: 'space-between',
    // alignItems: 'center'
  },
  titleText: {
    margin: 15,
    fontSize: 18,
    fontWeight: 'bold',
    color: 'white',
    // textAlign: 'center'
  },

  content: {
    flex: 1,
  },
  card: {
    top: 20,
    flex: 1,
    alignItems: 'center'
  },
  buttonDelivery: {
    marginTop: 10,
    paddingTop: 15,
    paddingBottom: 15,
    marginRight: 0,
    marginLeft: 0,
    backgroundColor: '#cce8f0',
    borderRadius: 10,
    borderWidth: 0,
    borderColor: '#fff',
    width: '50%',
    top: -20,
  },
  buttonPickup: {
    height: 50,
    marginTop: 10,
    paddingTop: 15,
    paddingBottom: 15,
    marginRight: 0,
    marginLeft: -30,
    backgroundColor: '#354175',
    borderRadius: 10,
    borderWidth: 0,
    borderColor: '#fff',
    width: '40%',
    top: -20,
  },

  submitOrder: {
    margin: 10,
    paddingTop: 15,
    paddingBottom: 5,
    backgroundColor: '#c9af6d',
    borderRadius: 10,
    borderWidth: 0,
    borderColor: '#fff',
  },

  topUseBalance: {
    flex: 0.5,
    backgroundColor: 'green',
    top: 20,
    margin: 10,
    padding: 10,
    paddingHorizontal: 30,
    borderRadius: 10,
    backgroundColor: '#CFB368',
    paddingBottom: -5
  },

  line: {
    borderBottomColor: '#c9af6d',
    borderBottomWidth: 2,
    alignSelf: 'stretch',
    width: "100%",
    height: 10,
    bottom: 5,
  },
  line2: {
    borderBottomColor: '#c9af6d',
    borderBottomWidth: 1,
    alignSelf: 'stretch',
    width: "100%",
    height: 10,
    bottom: 5,
  },
})

const mapDispatchToProps = (dispacth) => {
  return {

    setChangeOutletProps: (OutletChange) => dispacth({
      type: ActionType.SET_CHANGE_OUTLET,
      data: {
        outlet_id: OutletChange.outlet_id,
        name_outlet: OutletChange.name_outlet,
      }
    }),
    setTypePickup: (type) => dispacth({
      type: ActionType.SET_TYPE,
      data: {
        type_pickup: type
      }
    }),

    setCordinatProps: (cordinate) => dispacth({
      type: ActionType.SET_CORDINAT,
      data: {
        lat: cordinate.lat,
        long: cordinate.long,
      }
    }),

  }
}

const mapStateToProps = (state) => {
  return {

    // login
    email: state.email,
    outlet_id: state.outlet_id,
    name_outlet: state.name_outlet,
    session_id: state.session_id,
    password: state.password,
    fb_token: state.fb_token,
    device_id: state.device_id,
    os_version: state.os_version,
    os_name: state.os_name,
    app_version: state.app_version,
    isEmailverif: state.isEmailverif,
    proses: state.proses,
    pageEmailConfirmation: state.pageEmailConfirmation,
    language: state.language,
    lat: state.lat,
    long: state.long,
  }
}



export default connect(mapStateToProps, mapDispatchToProps)(Home)