import React, {Component} from 'react'
import {TouchableOpacity, View, StyleSheet, Text, ScrollView, RefreshControl, Animated, FlatList} from "react-native";
import LinearGradient from "react-native-linear-gradient";
import {BackgroundImage} from "../../components/BackgroundImage";
import IconMaterial from "react-native-vector-icons/MaterialCommunityIcons";
import Image from "react-native-fast-image";
import {NavigationEvents} from "react-navigation";
import {getListReward, getUserProfile} from "../../api/UserApi";
import {bindActionCreators} from "redux";
import {appSetUser} from "../../redux/app/action";
import {connect} from "react-redux";
import IndicatorLoading from "../../components/IndicatorLoading";

class AllRewards extends Component{
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      refreshing: false,
      all_rewards: [
        /*{source: require('../../../assets/images/reward_exam1.png'), title: 'ซื้อป๊อปสตาร์ 100 บาท แถมฟรีส่วนลดตั๋วหนัง 100บ... ', point: '1'},
        {source: require('../../../assets/images/reward_exam2.png'), title: 'Samosa หอมเครื่องเทศกรอบอร่อย  2 ชิ้น ในราคาเพียง 70 บาท', point: '2'},
        {source: require('../../../assets/images/reward_exam1.png'), title: 'เหล่ามินเนียน เตรียมบุกเมเจอร์ ให้สาวกชาวแก๊งค์ให้เก็บสะสม ', point: '3'},
        {source: require('../../../assets/images/reward_exam2.png'), title: 'M GEN แลก Points อร่อยคุ้มจาก แมคโดนัลด์', point: '4'},*/
      ],
      point: 0
    }
  }

  initData = () => {
    this.setState({
      isLoading: true,
      refreshing: true
    }, () => {
      Promise.all([
        this.getListReward(),
        this.getUserProfile()
      ]).then(() => {
        this.setState({
          isLoading: false,
          refreshing: false
        })
      });
    })
  };

  async getListReward () {
    let category_id = this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.id ? this.props.navigation.state.params.id : ''
    return await getListReward(category_id)
      .then(res => {
        if(res.ok){
          this.setState({
            all_rewards: res.data.data
          })
        }
      })
  };

  async getUserProfile () {
    return await getUserProfile()
      .then(res => {
        if(res.data && res.ok){
          this.setState({
            point: res.data.point_balance,
          }, () => {
            let user_data = this.props.user;
            user_data = {
              ...user_data,
              point: this.state.point
            }
            this.props.appSetUser(user_data)
          })
        }
      });
  }

  _onRefresh = () => {
    this.setState({
      isLoading: true,
      refreshing: true
    }, () => {
      this.initData()
    })
  };

  _keyExtractor = (item, index) => 'reward_' + index;

  renderItem = (item, index) => {
    return (
      <TouchableOpacity
        onPress={() => this.props.navigation.navigate('RewardDetail', {id: item.id})}
        style={[styles.rewardContain, {marginRight: index % 2 === 0 ? 10 : 0}, {width: index % 2 === 0 ? '48%' : '49.5%'}]}>
        <View style={{flex: 0.8}}>
          <Image source={{uri: item.image_reward ? item.image_reward : ''}} style={{height: '100%'}} resizeMode={'contain'} />
        </View>
        <View style={{flex: 0.2, padding: 8, flexDirection: 'column', justifyContent: 'center'}}>
          <Text style={{fontWeight: '600', fontFamily: 'Prompt-Regular',}}>{item.name}</Text>
          <Text style={{textAlign: 'right', color: '#FF6122', fontFamily: 'Prompt-Regular', fontWeight: '600'}}>{item.points_to_redeem} Point</Text>
        </View>
      </TouchableOpacity>
    )
  };

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <NavigationEvents
          onDidFocus={() => {
            this.setState({
              isLoading: true
            }, () => {
              this.initData()
            })
          }}
        />
        <BackgroundImage>
          <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#FFA800', '#E46F00']}
                          style={styles.pointContain}
          >
            <Text style={styles.textStyle}>{this.state.point} Points</Text>
            <IconMaterial name="star-circle-outline" color="white" size={40}/>
          </LinearGradient>
          <ScrollView contentContainerStyle={styles.contentContainer}
                      refreshControl={
                        <RefreshControl
                          refreshing={this.state.refreshing}
                          onRefresh={this._onRefresh}
                        />
                      }
                      showsVerticalScrollIndicator={false}
                      scrollEventThrottle={16}
                      // onScroll={Animated.event(
                      //   [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }]
                      // )}
          >
            <View style={{paddingHorizontal: 8, paddingBottom: 16}}>
              <FlatList
                data={this.state.all_rewards}
                renderItem={({ item, index }) => this.renderItem(item, index)}
                showsHorizontalScrollIndicator={false}
                keyExtractor={this._keyExtractor}
                numColumns={2}
                extraData={this.state.all_rewards}
                // onScroll={this._onCarouselScroll}
                ListEmptyComponent={() =>
                  <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', margin: 16,padding:16,borderRadius:5,backgroundColor:'white'}}>
                    <Text style={{fontSize: 16}}>No Rewards</Text>
                  </View>
                }
              />
            </View>
          </ScrollView>
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    );
  }
}

const styles = StyleSheet.create({
  textStyle: {
    color: 'white',
    fontFamily: 'Prompt-Regular',
    fontSize: 20,
    textAlign: 'right',
    fontWeight: '500',
    marginRight: 5
  },
  pointContain: {
    justifyContent: 'flex-end',
    paddingVertical: 12,
    paddingHorizontal: 5,
    flexDirection: 'row',
    alignItems: 'center'
  },
  rewardContain: {
    // flex: 1,
    // width: '48%',
    height: 300,
    backgroundColor: 'white',
    borderRadius: 6,
    marginTop: 16
  }
});

const mapDisPatchToProps = state => {
  return state.app
}

const propSet = dispatch => bindActionCreators({
  appSetUser,
}, dispatch)

export default connect(mapDisPatchToProps, propSet)(AllRewards)
