import React, {Component} from "react";
import { View, StyleSheet, Text, TouchableOpacity, FlatList, ScrollView, RefreshControl } from "react-native";
import FastImage from "react-native-fast-image";
import LinearGradient from "react-native-linear-gradient";
import IconMaterial from 'react-native-vector-icons/MaterialCommunityIcons'
import { NavigationEvents } from "react-navigation";
import { getLevelMemberDetail, getLevelMembership } from "../../api/UserApi";
import { BackgroundImage } from "../../components/BackgroundImage";
import IndicatorLoading from "../../components/IndicatorLoading";
import { t } from "../../utils/i18n";

class MembershipLevelDetail extends Component {
  constructor(props){
    super(props);
    this.state = {
      level_list: [],
      active_tab: 0,
      condition: [],
      privilege: [],
      isLoading: false,
      refreshing: false,
      member_data: null,
    }
  }

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

  async getLevelMember () {
    return await getLevelMembership()
      .then(res => {
        if(res.data && res.data.success){
          this.setState({
            member_data: res.data.data
          })
        }
      })
  }

  async getLevelDetail () {
    return await getLevelMemberDetail()
      .then(res => {
        if(res.data && res.data.success){
          this.setState({
            level_list: res.data.data,
            privilege: res.data.data && res.data.data.length > 0 ? res.data.data[0].privilege : [],
            active_tab: res.data.data && res.data.data.length > 0 ? res.data.data[0].id : 0,
            condition_age_of_rent: res.data.data && res.data.data.length > 0 ? res.data.data[0].age_of_rent : 0,
            condition_avg_paid_of_month: res.data.data && res.data.data.length > 0 ? res.data.data[0].avg_paid_of_month : 0
          })
        }
      })
  }

  _onRefresh = () => {
    this.initData()
  }

  handleChangeTab = (tab_id) => {
    let item = this.state.level_list.filter((item) => item.id === tab_id);
    let privilege = [];
    let condition_age_of_rent = 0;
    let condition_avg_paid_of_month = 0;
    if(item && item.length > 0) {
      privilege = item[0].privilege
      condition_age_of_rent = item[0].age_of_rent,
      condition_avg_paid_of_month = item[0].avg_paid_of_month
    }
    
    this.setState({
      active_tab: tab_id,
      privilege,
      condition_age_of_rent,
      condition_avg_paid_of_month
    })
  }

  render() {
    return (
      <ScrollView contentContainerStyle={{flex: 1}}
                  refreshControl={
                    <RefreshControl
                      refreshing={this.state.refreshing}
                      onRefresh={this._onRefresh}
                    />
                  }
                  showsVerticalScrollIndicator={false}
                  scrollEventThrottle={16}
      >
        <NavigationEvents
          onDidFocus={() => {
            this.initData()
          }}
        />
          <LinearGradient colors={['#FFA800', '#E46F00']} start={{x: 0, y: 0}} end={{x: 1, y: 0}}  style={{ flex: 0.3, padding: 16 }}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
              <View style={{flexDirection: 'row', alignItems: 'center'}}>
                <IconMaterial name="rhombus" size={25} color="white"/>
                <Text style={[styles.mainText, {paddingLeft: 5, fontWeight: '500', fontSize: 25}]}>{this.state.member_data && this.state.member_data.user_level}</Text> 
              </View>

              <View style={[styles.pointBox]}>
                <IconMaterial name="star-circle-outline" size={21} color="white"/>
                <Text style={[styles.mainText, {fontSize: 20, paddingLeft: 5, fontWeight: '600'}]}>
                  {this.state.member_data && this.state.member_data.point_balance ? parseFloat(this.state.member_data.point_balance).toLocaleString() : 0}<Text style={[styles.mainText, {fontSize: 12, fontWeight: 'normal'}]}> Points</Text>
                </Text>
              </View>
            </View>

            <View style={[styles.memberShipDetailBox]}>
              <View style={{flexDirection: 'row', flex: 1, alignItems: 'center'}}>
                <View style={{flex: 0.45}}>
                  <View>
                    <Text style={[styles.mainText, {color: 'black', fontSize: 16, textAlign: 'center'}]}>{t('min_rental')}</Text>
                    <Text style={[styles.mainText, {color: '#269A21', fontSize: 18, fontWeight: '500', textAlign: 'center'}]}>{this.state.member_data && this.state.member_data.age_of_rent ? this.state.member_data.age_of_rent : 0} <Text style={[styles.mainText, {color: 'black', fontSize: 20, fontWeight: 'normal'}]}>{t('month')}</Text></Text>
                  </View>
                </View>

                <View style={{flex: 0.05, marginLeft: -5}}>
                  <View style={{borderLeftWidth: 1, borderColor: 'rgba(0, 0, 0, 0.25)', height: '50%', alignSelf: 'center'}}></View>
                </View>

                <View style={{flex: 0.45, paddingLeft: 8}}>
                  <View>
                    <Text style={[styles.mainText, {color: 'black', fontSize: 16, textAlign: 'center'}]}>{t('avg_rent')}</Text>
                    <Text style={[styles.mainText, {color: '#269A21', fontSize: 18, fontWeight: '500', textAlign: 'center'}]}>{this.state.member_data && this.state.member_data.avg_paid_of_month ? parseFloat(this.state.member_data.avg_paid_of_month).toLocaleString() : 0} <Text style={[styles.mainText, {color: 'black', fontSize: 20, fontWeight: 'normal'}]}>{t('baht')}</Text></Text>
                  </View>
                </View>
              </View>
              
              <TouchableOpacity style={{backgroundColor: '#269A21', paddingVertical: 8, borderRadius: 6, marginTop: 10}}
                                onPress={() => this.props.navigation.navigate('MemberPoinExpire')}
              >
                <Text style={[styles.mainText, {textAlign: 'center', fontSize: 16}]}>{t('point_expire')}</Text>
              </TouchableOpacity>
            </View>
          </LinearGradient>

          <View style={{ flex: 0.7 }}>
            <View style={{flexDirection: 'row'}}>
            {
                this.state.level_list.map((item, index) => (
                  <TouchableOpacity onPress={() => {this.handleChangeTab(item.id)}} 
                    style={this.state.active_tab === item.id ? {borderBottomWidth: 4, borderBottomColor: '#DA7A16', flex: 1, paddingVertical: 12, height: '100%'} : {flex: 1, paddingVertical: 12, height: '100%'}}>
                    <Text style={[styles.mainText, {color: this.state.active_tab === item.id ? '#DA7A16' : 'rgba(0, 0, 0, 0.25)', textAlign: 'center'}]}>{item.name_th}</Text>
                  </TouchableOpacity>
                ))
            }
            </View>

            <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
              flex: 1,
              width: null,
              height: null,
              resizeMode: 'cover'
            }}>
              <BackgroundImage>
                <View style={{padding: 16}}>
                  <View style={{backgroundColor: '#00420A', borderRadius: 6, padding: 15}}>
                    <Text style={[styles.mainText, {paddingBottom: 2, fontWeight: '500'}]}>{t('condition')}</Text>
                     <View style={{paddingVertical: 2}}>
                      <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
                        <Text style={[styles.mainText]}>{t('min_rental')}</Text>
                        <Text style={[styles.mainText]}>{this.state.condition_age_of_rent} {t('month')}</Text>
                      </View>
                      
                      <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
                      <Text style={[styles.mainText]}>{t('min_avg_rent')}</Text>
                        <Text style={[styles.mainText]}>
                          {
                            this.state.condition_avg_paid_of_month 
                            ? parseFloat(this.state.condition_avg_paid_of_month).toLocaleString() : 0
                          } {t('baht')}
                        </Text>
                      </View>
                    </View>
                  </View>

                  <View style={{paddingVertical: 15, marginBottom: 100}}>
                    <Text style={[styles.mainText, {fontSize: 18}]}>{t('privilege')}</Text>
                    <View style={{ marginBottom: 20}}>
                      <FlatList
                          data={this.state.privilege}
                          renderItem={({ item }) => (
                            <View style={{
                              backgroundColor: 'white',
                              borderLeftWidth: 4, 
                              borderColor: '#FF9500', 
                              flexDirection: 'row', 
                              marginTop: 10, 
                              borderRadius: 5, 
                              padding: 10
                            }}>
                              <View style={{justifyContent: 'center', flex: 0.2}}>
                                <FastImage source={{uri: item.icon}} 
                                style={{width: 50, height: 50}} resizeMode="contain"/>
                              </View>
                              <View style={{flex: 0.8}}>
                                <Text style={[styles.mainText, {fontSize: 16, color: '#DA7A16'}]}>{item.topic}</Text>
                                <Text style={[styles.mainText, {fontSize: 14, color: 'rgba(0, 0, 0, 0.5)'}]}>{item.detail}</Text>
                              </View>
                            </View>
                          )}
                          pagingEnabled={true}
                          extraData={this.state}
                          keyExtractor={(item, index) => 'privilege_' + index}
                      />
                    </View>
                    
                  </View>
                </View>
              </BackgroundImage>
            </LinearGradient>
          </View>
          <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </ScrollView>
    )
  };
}

const styles = StyleSheet.create({
  mainText: {
    fontFamily: 'Prompt-Regular',
    fontSize: 16,
    color: 'white'
  },
  pointBox: {
    flexDirection: 'row',
    backgroundColor: 'rgba(255, 255, 255, 0.25)',
    borderRadius: 100,
    alignItems: 'center',
    paddingHorizontal: 8
  },
  memberShipDetailBox: {
    backgroundColor: 'white',
    borderRadius: 8,
    padding: 16,
    flex: 1,
    marginTop: 10
  }
});

export default MembershipLevelDetail;