import React from 'react';
import { View, Text, StyleSheet, ScrollView, Platform, TouchableOpacity, Image, FlatList, Button, StatusBar, ActivityIndicator, Alert, Modal } from 'react-native';
import Axios from 'axios';
import Item from './Item';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import CurrencyFormat from 'react-currency-format';
import _ from 'lodash';
import session from '../function/session';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import * as Device from 'expo-device';
import NumberFormat from 'react-number-format';
import i18n from 'i18n-js';
import Constants from 'expo-constants';
import requestParams from '../helper/requestParams';
import CustomIosStatusBar from './CustomIosStatusBar';
import Spinner from 'react-native-loading-spinner-overlay';

class MenuSelection extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      listCategory: [],
      listMenu: [],
      list_orders: [],
      outlet_id: '',
      qty: 1,
      order_list: [],
      list_cart: [],
      indicator: true,
      my_lat: 0,
      my_long: 0,
      data: [],
      data_before_search: '',
      note: ''
    }
  }

  componentDidMount() {

    if (this.props.outlet_id != '') {
      this.getMenuList()
    } else {
      this.setState({
        indicator: true
      })
      this._getPermissions()
    }
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      this.setState({
        indicator: true
      })
      if (this.props.outlet_id != '') {
        this.getMenuList()
      } else {
        this.setState({
          indicator: true
        })
        this._getPermissions()

      }
    });
  }

  shouldComponentUpdate() {
    return true
  }

  componentWillUnmount() {
    this._unsubscribe();
  }


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

      Alert.alert(i18n.t('tryItRealDevice'))
    } 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
    })

    this._getOutletClosest();
  }

  _getOutletClosest() {

    let params = Object.assign(requestParams, {
      session_id: this.props.session_id,
      lat: this.state.my_lat,
      long: this.state.my_long
    })
    // console.log(params);
    Axios.post(this.props.BASE_URL + '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.getMenuList()
    }).catch(error => {
      const { navigation } = this.props
      let response = error.response.data
      session(response, navigation)
      Alert.alert(response.msg);
    })
  }

  getMenuList() {

    let params = Object.assign(requestParams, {
      outlet_id: this.props.outlet_id
    })
    // console.log("INI YA " + params)
    Axios.post(this.props.BASE_URL + 'crm/v2/menu/get_list', params).then(res => {

      let data = res.data.data



      // let last_category = ''
      // let list_menu = []

      // for (let i = 0; i < data.menu.length; i++) {
      //   const row = data.menu[i];
      //   // cari sudah ada belum di redux
      //   let is_xist = this.props.order_item.find(item => row.id == item.id)
      //   if (is_xist) {
      //     row['qty'] = is_xist.quantity
      //   } else {
      //     row['qty'] = 0
      //   }

      //   if (last_category != row.category.name) {
      //     let category = {
      //       "id": row.category.id,
      //       "name": row.category.name,
      //       "code": "CATEGORY"
      //     }
      //     list_menu.push(category)
      //     list_menu.push(row)
      //     last_category = row.category.name
      //   } else {
      //     list_menu.push(row)
      //   }
      // }
      // this.setState({
      //   listMenu: list_menu
      // })

      this.props.updateMenu(data.menu)
      this.setState({
        listCategory: data.category,
        listMenu: data.menu,
        indicator: false,
        data_before_search: this.props.menu_item,
        indicator: false
      })

    }).catch(error => {
      const { navigation } = this.props
      let response = error.response.data
      session(response, navigation)
      Alert.alert(response.msg);
    })
  }

  filterSubcategory = (item) => {
    try {
      let index_start = _.findIndex(this.props.menu_item, ['name', item.name])
      let index_next_category = _.findIndex(this.state.listCategory, ['name', item.name]) + 1
      let next_category = this.state.listCategory[index_next_category]
      let index_end = _.findIndex(this.props.menu_item, ['name', next_category.name])

      if (index_end < 0) {
        index_end = this.props.menu_item.length;
        console.log(index_end)
      }
      let filter_item = this.props.menu_item.slice(index_start, index_end);
      this.setState({
        data_before_search: filter_item
      })

    } catch (error) {

      let index_start = _.findIndex(this.props.menu_item, ['name', item.name])
      let index_end = parseInt(this.props.menu_item.length)
      let filter_item = this.props.menu_item.slice(index_start, index_end);

      this.setState({
        data_before_search: filter_item
      })

    }

  }

  handleVoucherSelect() {
    //SPINNER ON 
    this.setState({
      spinner: true,
    })
    //CEK TYPE TRANSAKSINYA DELIVERY OR PICKUP, DICEK UNTUK DI MASUKAN DI PARAMATER PEMANGGILAN API
    let type_trans = ""
    if (this.props.type_pickup == true) {
      type_trans = 'Pickup'
    } else {
      type_trans = 'Delivery'
    }

    let params = {
      session_id: this.props.session_id,
      trans_type: type_trans,
      order_item: this.props.order_item,
      reward_id: this.props.voucher.id,
      delivery_charge: this.props.grabamount,
    }
    // MULAI DISINI PEMANGGILAN API DI MULAI, KALAU BERHASIL SET VALUE VOUCHER NYA DAN SPINER DIMATIKAN, KALAU GAGAL CABUT SESSION VOUCHER DAN SPINNER DI MATIKAN
    Axios.post(this.props.BASE_URL + 'crm/v2/reward/get_value', params).then(res => {

      let voucherProps = {
        value_voucher: res.data.reward,
        voucher: res.data.reward
      }

      this.props.setVoucher(voucherProps);
      this.setState({
        spinner: false,
      })
    }).catch(error => {
      try {
        let response = error.response.data
        Alert.alert("", response.msg)
        this.setState({
          spinner: false,
        })
      } catch (error) {
        Alert.alert("", error.toString())
        this.setState({
          spinner: false,
        })
      }
    })
  }

  renderTabBar = ({ item }) => {
    return (
      <View style={{ flex: 0.5 }}>
        <TouchableOpacity onPress={() => this.filterSubcategory(item)}>
          {item.image === '' ? (
            <View style={{ height: 60, width: 60, top: 5 }} />
          ) :
            (
              <Image style={{ height: 60, width: 60, top: 5 }} source={{ uri: item.image }} />
            )
          }
        </TouchableOpacity>
      </View>
    )
  }

  renderItem = ({ item, index }) => {
    return (
      <View>
        <Item navigation={this.props.navigation}
          item={item}
          handleAdd={() => this.handleAdd(item, index)}
          handleMin={() => this.handleMin(item, index)}
        />
      </View>
    )
  }


  refresh() {
    this.setState({ isFetching: true }, function () { this.getMenuList() });
  }

  scrollToItem = () => {
    this.props._scrollView.scrollTo({ x: 0, y: 1 * 100 });
  }

  handleAdd(item, index) {

    const order_item = {
      id: item.id,
      code: item.code,
      name: item.name,
      description: item.description,
      note: item.note,
      image: item.image,
      price: parseInt(item.price),
    }

    let res = this.props.addToChart(order_item)
    if (this.props.value_voucher !== "") {
      if (this.props.value_voucher.reward.type == 'percentage') {
        this.handleVoucherSelect()
      }
    }
    // console.log('After add : ' + JSON.stringify(res))

    // const list_order_item = this.props.order_item;
    // let is_xist = list_order_item.find(row => row.id == item.id)

    // let quantity = 1
    // if (is_xist) {
    //   console.log(is_xist.name + ' Item Sudah ada dengan quantity : ' + is_xist.quantity)
    //   quantity = is_xist.quantity
    // }


    // const listMenu = [...this.state.listMenu]
    // listMenu[index].qty = quantity
    // console.log("HASIL : " + listMenu[index].qty)
    // this.setState({
    //   listMenu
    // })
  }

  clearNegatif(item, index) {
    const list_order_item = this.props.order_item;
    for (let i = 0; i < list_order_item.length; index++) {
      const row = list_order_item[i];
      if (row.quantity !== 0) {
        const order_item = {
          id: item.id,
          name: item.name,
          price: item.price,
        }
        this.props.reduceQuantityItem(order_item)
      }

    }
  }

  // onChange(params) {
  //   console.log(params);
  // }


  handleMin(item, index) {
    const list_order_item = this.props.order_item;
    let is_xist = list_order_item.find(row => row.id == item.id)
    if (is_xist) {
      if (is_xist.quantity != 0) {
        const order_item = {
          id: item.id,
          name: item.name,
          price: item.price,

        }
        this.props.reduceQuantityItem(order_item)

      }
    }
    if (this.props.value_voucher !== "") {
      if (this.props.value_voucher.reward.type == 'percentage') {
        this.handleVoucherSelect()
      }
    }
  }

  scrollToIndex = (item) => {
    // let start = new Date()
    // let end = new Date()
    // let diff = end - start / 1000   
    // console.log("TIME : "+diff)
    try {
      index = _.findIndex(this.props.menu_item, ['name', item.name])
      if (index > -1) {
        this.flatListRef.scrollToIndex({ animated: true, index: index });
      }
    } catch (error) {
      // index = _.findIndex(this.props.menu_item, ['name', item.name])
      // this.flatListRef.scrollToIndex({ animated: true, index: this.setLastIndex });
    }
  }

  // getItemLayout = (data, index) => (
  //   {
  //     length: 100,
  //     offset: 100 * index,
  //     index
  //   }
  // )

  // setLastIndex = (index) => {
  //   las
  //   lastIndex = index
  // }


  render() {
    return (
      <View style={styles.container}>
        <Spinner visible={this.state.spinner} textContent={'Loading...'} textStyle={{ color: "white" }} />
        {Platform.OS === 'ios' ? (
          <CustomIosStatusBar color='#CFB368' />
        ) : (
            <StatusBar backgroundColor='#CFB368' />
          )}
        <View style={{ flex: 0.5, paddingTop: StatusBar.currentHeight, marginHorizontal: 10, borderBottomWidth: 1, paddingBottom: 5, borderColor: '#838383' }}>
          <FlatList horizontal={true} style={{ flexDirection: 'row' }}
            showsHorizontalScrollIndicator={false}
            data={this.state.listCategory}
            renderItem={this.renderTabBar}
            keyExtractor={(item) => item.id}
            maxToRenderPerBatch={10}

          />
        </View>
        {/* <View style={{ height: 1, backgroundColor: 'grey', marginRight: 10, marginLeft: 10, marginTop: 5, }}></View> */}
        <View style={{ flex: 3, marginRight: 10, marginLeft: 10 }}>
          {this.state.indicator == true ? (
            <ActivityIndicator style={{ top: 10 }} size="large" color="#c9af6d" />
          ) : (
              this.state.data_before_search.length > 0 ? (
                <FlatList
                  data={this.state.data_before_search}
                  renderItem={this.renderItem}

                  keyExtractor={item => item.id}

                />
              ) : (
                  <Text style={{ flexWrap: 'wrap', fontFamily: 'Gotham-Light', color: '#b1b1b2', textAlign: 'center', top: 20 }}> {i18n.t('itemnotfound')}</Text>
                )
            )}
        </View>
        <View>
        </View>
        <View style={{ height: 1, backgroundColor: 'grey', marginRight: 10, marginLeft: 10 }}></View>
        <View style={{ height: 70 }}>
          <View style={{ flex: 1, flexDirection: 'row' }}>
            <View style={{ flex: 1, justifyContent: 'flex-start' }}>
              <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', textAlign: 'center', top: 10, color: '#838383' }}>{this.props.order_quantity} Item {this.props.type_pickup == true ? (null) : (
                <NumberFormat decimalScale={0} value={this.props.grabamount} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', top: 20, textAlign: 'center', color: '#838383' }}>/ {i18n.t('rateDelivery')} Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
              )} </Text>
              <NumberFormat decimalScale={0} value={this.props.order_total} renderText={value => <Text style={{ fontSize: 20, fontFamily: 'Gotham-Light', top: 20, textAlign: 'center', color: '#838383' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
            </View>
            <View style={{ flex: 1, height: 100 }}>
              <TouchableOpacity onPress={() => this.props.navigation.navigate('Shopping Cart')}>
                <View>
                  {
                    this.props.language == 'id' ? (
                      <View style={{ height: 40, borderRadius: 10, width: '86%', backgroundColor: '#CFB368', marginRight: 20, marginLeft: 16, top: 15, flexDirection: 'row', marginBottom: 30 }}>
                        <Image source={(require('../assets/icon/icon-order.png'))} style={{ height: 40, width: 40, tintColor: 'white', }}></Image>
                        <Text style={{ fontFamily: 'Gotham-Light', color: 'white', fontSize: 16, alignSelf: 'center', textAlign: 'center' }}>{i18n.t('Viewcart')}</Text>
                      </View>
                    ) : (
                        <View style={{ height: 40, borderRadius: 10, width: '68%', backgroundColor: '#CFB368', marginRight: 20, marginLeft: 40, top: 15, flexDirection: 'row', marginBottom: 30 }}>
                          <Image source={(require('../assets/icon/icon-order.png'))} style={{ height: 40, width: 40, tintColor: 'white', }}></Image>
                          <Text style={{ fontFamily: 'Gotham-Light', color: 'white', fontSize: 16, alignSelf: 'center', textAlign: 'center' }}>{i18n.t('Viewcart')}</Text>
                        </View>
                      )
                  }
                </View>
              </TouchableOpacity>
            </View>
          </View>
          <View>
          </View>
        </View>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',

  },


  // shadow: {
  //   borderWidth:1,
  //   borderColor: '#ddd',
  //   borderBottomWidth: 0,
  //   shadowColor: '#000',
  //   shadowOffset: { width: 0, height: 0 },
  //   shadowOpacity: 10,
  //   shadowRadius: 0,
  //   elevation: 0,
  //   marginTop: 10,
  //   flex: 0.5,
  //   height: 50,
  // }
})

const mapStateToProps = (state) => {

  return {
    type_pickup: state.type_pickup,
    BASE_URL: state.BASE_URL,
    session_id: state.session_id,
    grabamount: state.grabamount,
    outlet_id: state.outlet_id,
    order_item: state.order_item,
    order_quantity: state.order_quantity,
    order_total: state.order_total,
    quantity: state.quantity,
    address: state.address,
    menu_item: state.menu_item,
    language: state.language,
    os_version: state.os_version,
    os_name: state.os_name,
    app_version: state.app_version,
    value_voucher: state.value_voucher,
    voucher: state.voucher,
  }
}

const mapDispatchToProps = (dispacth) => {
  return {
    updateMenu: (menu) => dispacth({
      type: ActionType.UPDATE_MENU,
      data: {
        menu: menu
      }
    }),
    addToChart: (item) => dispacth({
      type: ActionType.ADD_TO_CHART,
      data: {
        item: item
      }
    }),
    reduceQuantityItem: (item) => dispacth({
      type: ActionType.REDUCE_QUANTITY_ITEM,
      data: {
        item: item
      }
    }),
    setChangeOutletProps: (OutletChange) => dispacth({
      type: ActionType.SET_CHANGE_OUTLET,
      data: {
        outlet_id: OutletChange.outlet_id,
        name_outlet: OutletChange.name_outlet,
      }
    }),
    setVoucher: (voucherProps) => dispacth({
      type: ActionType.SET_VOUCHER,
      data: {

        voucher: voucherProps.voucher,
        value_voucher: voucherProps.value_voucher,

      }
    }),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MenuSelection)


