import React from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Image, FlatList, Button, Alert, StatusBar, SafeAreaView, SectionList } 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 Constants from "expo-constants";
import { Ionicons, MaterialCommunityIcons, MaterialIcons, AntDesign } from '@expo/vector-icons';
// import { range } from 'lodash';
import _ from 'lodash';

class MenuSelection extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      listCategory: [],
      list_category: [],
      listMenu: [],
      list_orders: [],
      outlet_id: '',
      qty: 1,
      order_list: [],
      list_cart: [],
    }
  }
  componentDidMount() {
    this.getMenuList()
    // console.log("INI TOTAL ORDER : " + this.props.orders)
    // console.log("INI TOTAL QTY :" + this.props.quantity)
    console.log("INI ORDERAN NYA  :" + JSON.stringify(this.props.cart_shop))
  }

  getMenuList() {
    let params = {

      outlet_id: "dec1abbb-95d0-46ae-a6cd-2bf306590f15"
    }
    Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/menu/get_list', params).then(res => {

      let data = res.data.data
      this.setState({
        listCategory: data.category,
        listMenu: data.menu
      })

     
      let last_category = ''
      let list_menu = []


      for (let i = 0; i < data.menu.length; i++) {
        
        const row = data.menu[i];
        
        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.state.listMenu.map((i => {
        i.qty=0
      }))
      console.log('After :  ' + JSON.stringify(list_menu))
      this.setState({
        listMenu:list_menu
      })
      
    })

  }
  renderTabBar = ({ item }) => {
    return (
      <View style={{ margin: 10 }}>
        <TouchableOpacity>
          <Image style={{ height: 50, width: 50, borderRadius: 25 }} source={{ uri: item.image }} />
          <Text>{item.name}</Text>
        </TouchableOpacity>
      </View>
    )
  }
  // scroll(item) {
  //   this.refs._scrollView.scrollTo(0);
  // }

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

  // handleRemove(item, index) {
  //   const listMenu = [...this.state.listMenu]
  //   if (listMenu[index].qty !== 0) {
  //     listMenu[index].qty -= 1
  //     this.setState({
  //       listMenu
  //     })
  //   }

  // }

  scrollToItem = () => {
    // let newData = []
    // newData.push(this.state.listMenu)

    // console.log("DATA  " + JSON.stringify(newData))
    // newData.map((item => {
    //    let abc =  item[0].category
    // }))

    this.props._scrollView.scrollTo({ y: 1 * 100 });

  }

  handleAdd(item, index) {
    const order_item = {
      id: item.id,
      name: item.name,
      price: item.price,
      image: item.image
    }

    this.props.addToChart(order_item)

    const list_order_item = this.props.order_item;
    let quantity = 0
    for (let i = 0; i < list_order_item.length; i++) {
      const row = list_order_item[i];
      if (row.id == item.id) {
        quantity = row.quantity
      }
    }

    const listMenu = [...this.state.listMenu]
    listMenu[index].qty = quantity
    this.setState({
      listMenu
    })
  }

  handleMin(item, index) {
    const order_item = {
      id: item.id,
      name: item.name,
      price: item.price,

    }
    this.props.reduceQuantityItem(order_item)
    const list_order_item = this.props.order_item;
    let quantity = 0
    if (item.qty == 0) {
        item.qty = 0
    }else{
      for (let i = 0; i < list_order_item.length; i++) {
        const row = list_order_item[i];
        if (row.id == item.id) {
          quantity = row.quantity
        }
      const listMenu = [...this.state.listMenu]
      listMenu[index].qty = quantity
      this.setState({
        listMenu
      })
    }
    }
      
  }

  render() {
    return (
      <View style={styles.container}>
        <StatusBar hidden={true} />
        <View style={{ flex: 0.7, height: 90, flexDirection: 'row', borderWidth: 1, }}>
          <FlatList horizontal={true} style={{ flexDirection: 'row' }}
            showsHorizontalScrollIndicator={false}
            data={this.state.listCategory}
            renderItem={this.renderTabBar}
            keyExtractor={(item) => item.id}
          />
        </View>
        <View style={{ flex: 3 }}>
          <FlatList
            data={this.state.listMenu}
            renderItem={({ item, index }) => (
              <Item navigation={this.props.navigation}
                item={item}
                handleAdd={() => this.handleAdd(item, index)}
                handleMin={() => this.handleMin(item, index)}
              />
            )}
            keyExtractor={item => item.id}
          />
        </View>
        <View style={styles.shadow}>
          <View style={{ flexDirection: 'row', }}>
            <Text style={{ fontSize: 12, margin: 10 }}> Price Estimation / Item {this.props.order_quantity}  </Text>
            <Text style={{ fontSize: 20, margin: 10, marginBottom: 10 }}> Rp. {this.props.order_total}</Text>
          </View>
          <View>
            <Button title="VIEW CART" onPress={() => this.props.navigation.navigate('Shopping Cart')}></Button>
          </View>
          <View>
          </View>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  shadow: {
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 10,
    shadowRadius: 5,
    elevation: 1,
    marginTop: 10,
    flex: 0.8,
    height: 80,
  }
})

const mapStateToProps = (state) => {
  console.log(state)
  return {
    session_id: state.session_id,
    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
    // qty: state.qty,
    // totalOrder: state.totalOrder,
    // totalQty: state.totalQty,

    // orders: state.orders,
    // cart_shop: state.cart_shop,


  }
}

const mapDispatchToProps = (dispacth) => {
  return {
    setCartInsert: (data) => dispacth({
      type: ActionType.SET_CHANGE_SHOP,
      data: {
        id: data.cart_shop
      }
    }),
    addToChart: (item) => dispacth({
      type: ActionType.ADD_TO_CHART,
      data: {
        item: item
      }
    }),
    //REDUCE QUANTITY ITEM
    reduceQuantityItem: (item) => dispacth({
      type: ActionType.REDUCE_QUANTITY_ITEM,
      data: {
        item: item
      }
    }),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(MenuSelection)























