/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  PixelRatio,
  Text,
  RefreshControl,
  FlatList,
  ProgressBarAndroid,
  ProgressViewIOS,
  Alert,
  StatusBar,
} from 'react-native';
import BaseScreen from './../BaseScreen';
import {
  responsiveHeight,
  responsiveWidth,
} from 'react-native-responsive-dimensions';
import {listAllMembers} from './../../webservice/MemberGeolocatedApi';
import {listFreeCodesSuperViseur} from './../../webservice/NetworkApi';
import {
  readUser,
  listDemandAdhesion,
  acceptDemandAdhesion,
  deleteUser,
} from '../../webservice/AuthApi';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Icons from 'react-native-vector-icons/Ionicons';
import Swipeout from 'react-native-swipeout';
import {theme} from '../BaseScreen';
require('./../../utils/Translations');
import I18n from 'react-native-i18n';
const route = require('./../../route.json');
import LottieView from 'lottie-react-native'; // if you have "esModuleInterop": true
import {
  IndicatorViewPager,
  PagerTabIndicator,
} from 'react-native-best-viewpager';
import Tag from '../../components/Tag';

import {
  Card,
  CardTitle,
  CardContent,
  CardAction,
  CardButton,
  CardImage,
} from 'react-native-material-cards';
let moment = require('moment-timezone');
import 'moment/locale/fr';
import 'moment/locale/es-us';
import 'moment/locale/en-au';
import 'moment/locale/en-ca';
import 'moment/locale/en-ie';
import 'moment/locale/en-il';
import 'moment/locale/en-nz';
import {Header} from 'react-native-elements';
import {IlinkEmitter} from '../../utils/events';
import DeviceInfo from 'react-native-device-info';
import {Color} from '../../config/Color';
import {Typography, FontWeight} from '../../config/typography';
import {thousandsSeparators} from '../../utils/UtilsFunction';
const thousands = require('thousands');

var users = null;
var chart = null;

export default class SuperViseurGroupeHome extends BaseScreen {
  static tabsStyle: {
    tabBarButtonColor: '#ff0000',
  };
  static navigatorStyle = {
    tabBarHidden: false,
    topTabTextColor: '#ffffff',
    topTabsHeight: 70,
    topTabTextFontFamily: 'BioRhyme-Bold',
    selectedTopTabTextColor: '#ff505c',

    statusBarColor: theme.primaryDark,
    navBarBackgroundColor: theme.primary,
    navBarTextColor: 'white',
    navBarButtonColor: 'white',
    // Icons
    topTabIconColor: '#ffffff',
    selectedTopTabIconColor: '#ff505c',

    // Tab indicator
    selectedTopTabIndicatorHeight: PixelRatio.get() * 2,
    selectedTopTabIndicatorColor: '#ff505c',
  };
  static options(passProps) {
    return {
      topBar: {
        rightButtons: [],
      },
    };
  }
  static navigationOptions = ({navigation}) => {
    return {
      title: I18n.t('GROUP_MANAGE'),
      drawerLabel: navigation.getParam('name', I18n.t('GROUP_MANAGE')),
      drawerIcon: ({tintColor}) => <Icon name={'people'} size={24} />,
    };
  };
  constructor(props) {
    super(props, true);
    this.state = SuperViseurGroupeHome.initState();

    readUser().then(user => {
      this.setState({user: user});
      listFreeCodesSuperViseur(user.code_membre).then(codes => {
        console.log('codes', codes);
        if (codes.success != undefined) {
          this.setState({freeCodes: codes.networks});
        }
      });
    });
    listAllMembers().then(data => {
      console.log(data);
      if (data !== null) {
        this.setState({
          listmembers: data,
          isLoading: false,
          isRefreshing: false,
        });
      }
    });
    this._populateIcons().then(values => {
      this.setState({usersicon: values[0], charticon: values[1]});
    });
    listDemandAdhesion().then(items => {
      console.log(items);
      let filtereds = [];
      items.forEach(item => {
        let b = false;
        filtereds.forEach(f => {
          if (f.code_membre === item.code_membre) {
            b = true;
          }
        });
        if (!b) filtereds.push(item);
      });
      console.log('filtered', filtereds);
      if (items !== undefined) {
        this.setState({demands: filtereds, isLoadingDemand: false});
      }
    });
    IlinkEmitter.on('langueChange', this.updateLangue.bind(this));
    this.currentLocale = I18n.locale.includes('fr') ? 'fr' : 'en-gb';
    moment.locale(this.currentLocale);
  }
  updateLangue() {
    this.props.navigation.setParams({name: I18n.t('GROUP_MANAGE')});
    this.forceUpdate();
  }
  static initState() {
    return {
      enabledListMembers: true,
      listmembers: [],
      usersicon: null,
      isLoadingDemand: true,
      charticon: null,
      isRefreshing: false,
      user: {},
      freeCodes: [],
      isLoading: true,
    };
  }
  render() {
    return (
      <View style={{flex: 1, marginBottom: 10}}>
        <StatusBar
          backgroundColor="#00000030"
          barStyle="light-content"
          translucent={false}
        />
        <IndicatorViewPager
          style={{flex: 1}}
          indicator={
            this.state.user.category === 'hyper'
              ? this._renderTabIndicatorAdmin()
              : this._renderTabIndicator()
          }>
          {this.state.isLoading
            ? this._renderLoadingItems()
            : this._renderListMembers()}
          {this.state.isLoadingDemand
            ? this._renderLoadingItems()
            : this.state.user.category === 'hyper'
            ? this._renderListDemandAdhesion()
            : this._renderListCodeUnused()}
        </IndicatorViewPager>
      </View>
    );
  }

  _populateIcons = function () {
    return new Promise(function (resolve, reject) {
      Promise.all([
        Icon.getImageSource('users', 30),
        Icon.getImageSource('chart-pie', 30),
      ])
        .then(values => {
          users = values[0];
          chart = values[0];
          resolve(values);
        })
        .catch(error => {
          console.log(error);
          reject(error);
        })
        .done();
    });
  }

  _renderTabIndicatorAdmin() {
    let tabs = [
      {
        text: I18n.t('MEMBER_LIST'),
        iconSource: this.state.usersicon,
      },
      {
        text: I18n.t('MEMBERSHIP_REQUEST'),
        iconSource: this.state.charticon,
      },
    ];
    return (
      <PagerTabIndicator
        style={{
          height: responsiveHeight(8),
        }}
        tabs={tabs}
      />
    );
  }

  _renderTabIndicator() {
    let tabs = [
      {
        text: I18n.t('MEMBER_LIST'),
        iconSource: this.state.usersicon,
      },
    ];
    return (
      <PagerTabIndicator
        style={{
          height: responsiveHeight(8),
        }}
        tabs={tabs}
      />
    );
  }

  _renderListMembers() {
    return (
      <View>
        <FlatList
          style={{flex: 1, backgroundColor: '#EEE'}}
          data={
            this.state.listmembers instanceof Array
              ? this.state.listmembers
              : this.state.listmembers.datas
              ? this.state.listmembers.datas
              : []
          }
          ListEmptyComponent={() => {
            return (
              <View style={{flex: 1}}>
                <View
                  style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginTop: 100,
                  }}>
                  <LottieView
                    style={styles.lottie}
                    source={require('./../../datas/json/629-empty-box.json')}
                    autoPlay
                    loop
                  />
                  <Text style={styles.text}>{I18n.t('NO_MEMBERS')}</Text>
                </View>
              </View>
            );
          }}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              colors={[
                theme.primary,
                theme.purpleLight,
                theme.reddeconnect,
                theme.accentLight,
              ]}
              onRefresh={() => {
                this.setState({isRefreshing: true});
                listAllMembers().then(data => {
                  console.log('from refresh', data);
                  if (data !== null && data.datas) {
                    this.setState({
                      listmembers: data,
                      isLoading: false,
                      isRefreshing: false,
                    });
                  }
                });
              }}
            />
          }
          renderItem={({item}) => this.renderMembers(item)}
        />
      </View>
    );
  }

  _renderLoadingItems() {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <ProgressBarAndroid />
      </View>
    );
  }

  renderMembers(item) {
    var re = moment.tz(item.created_at, moment.tz.guess()).format();
    re = moment(re).fromNow();
    if (true) {
      return (
        <Card>
          <CardTitle title={item.lastname} subtitle={item.adresse} />
          <CardContent>
            <View
              style={{flexDirection: 'row', justifyContent: 'space-between'}}>
              <View style={{flex: 1, alignItems: 'flex-start'}}>
                <View
                  style={{
                    flexDirection: 'row',
                    backgroundColor: theme.primary,
                    justifyContent: 'center',
                    marginRight: 10,
                    width: 160,
                    marginTop: 5,
                    alignItems: 'center',
                    borderRadius: 10,
                  }}>
                  <Icon
                    name={'phone'}
                    color={'white'}
                    size={24}
                    style={styles.callIcon}
                  />
                  <Text style={styles.phone}>{item.phone}</Text>
                </View>
              </View>

              <View
                style={{
                  width: 1,
                  backgroundColor: Color.borderColor,
                  marginTop: -20,
                }}
              />

              <View style={{flex: 1, flexDirection: 'column', marginTop: -15}}>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginTop: -10,
                  }}>
                  <View
                    style={[
                      styles.circlePoint,
                      {backgroundColor: Color.whiteColor},
                    ]}>
                    <Icons
                      name="md-wallet"
                      size={32}
                      color={Color.primaryColor}
                    />
                  </View>
                  <View>
                    <Text
                      style={
                        ([Typography.title3, Color.primaryColor],
                        {marginBottom: 1})
                      }>
                      {I18n.t('PRINCIPAL_ACCOUNT_TITLE')}
                    </Text>
                    <Text style={[Typography.body2]}>
                      {item.balance_princ === null
                        ? 0
                        : thousands(item.balance_princ, ' ')}
                    </Text>
                  </View>
                </View>

                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginTop: -10,
                  }}>
                  <View
                    style={[
                      styles.circlePoint,
                      {backgroundColor: Color.whiteColor},
                    ]}>
                    <Icons
                      name="md-cash"
                      size={32}
                      color={Color.primaryColor}
                    />
                  </View>
                  <View>
                    <Text
                      style={
                        ([Typography.title3, Color.primaryColor],
                        {marginBottom: 1})
                      }>
                      {I18n.t('COMMISSION_ACCOUNT_TITLE')}
                    </Text>
                    <Text style={Typography.body2}>
                      {item.balance_com === null
                        ? 0
                        : thousands(item.balance_com, ' ')}
                    </Text>
                  </View>
                </View>
              </View>
            </View>

            {/*                               <View Style={{ flex: 1, flexDirection: 'row' }}>
                                   <View Style={{ flex: 1 }} />

                                   <View style={{
                                        flexDirection: 'row',
                                        backgroundColor: theme.primary,
                                        marginRight: 10,
                                        width: 150,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        borderRadius: 10,
                                   }}><Icon name={"phone"} color={"white"} size={24}
                                        style={styles.callIcon} />
                                        <Text style={styles.phone}>{item.phone}</Text>
                                   </View>
                                   </View> */}
          </CardContent>
          <CardAction separator={true} inColumn={false}>
            <CardButton
              onPress={() => {
                Alert.alert(
                  I18n.t('TITLE_SUPPRESS_CONFIRM'),
                  I18n.t('TEXT_SUPPRESS_CONFIRM'),
                  [
                    {text: I18n.t('NO'), onPress: () => {}},
                    {
                      text: I18n.t('YES'),
                      onPress: () => {
                        deleteUser(item).then(() => {
                          this.setState({isLoading: true});
                          listAllMembers().then(data => {
                            console.log(data);
                            if (data !== null) {
                              this.setState({
                                listmembers: data,
                                isLoading: false,
                                isRefreshing: false,
                              });
                            }
                          });
                        });
                      },
                      style: 'cancel',
                    },
                  ],
                );
              }}
              title={I18n.t('DELETE_GEOLOCATED_USER')}
              color="crimson"
            />
          </CardAction>
        </Card>
      );
    } else
      return (
        <View>
          <Swipeout
            left={[
              {
                text: I18n.t('DELETE_GEOLOCATED_USER'),
                type: 'delete',
                autoClose: true,
                onPress: function () {
                  Alert.alert(
                    'Confirmations de suppression',
                    'Voulez vous vraiment supprimer cette utilisateur ?',
                    [
                      {text: 'Non', onPress: () => {}},
                      {
                        text: 'Oui',
                        onPress: () => {
                          deleteUser(item).then(() => {
                            this.setState({isLoading: true});
                            listAllMembers().then(data => {
                              if (data !== null) {
                                this.setState({
                                  listmembers: data,
                                  isLoading: false,
                                });
                              }
                            });
                          });
                        },
                        style: 'cancel',
                      },
                    ],
                  );
                },
              },
            ]}
            buttonWidth={responsiveWidth(40)}>
            <View
              style={{
                height: 200,
                marginBottom: 10,
                flex: 1,
                backgroundColor: 'white',
              }}>
              <Text style={styles.name}>{item.firstname}</Text>

              <Text style={styles.surname}>{item.lastname}</Text>
              <View
                style={{
                  flexDirection: 'row',

                  marginRight: 20,
                  justifyContent: 'flex-end',
                  alignItems: 'center',
                }}>
                <Icon
                  name={'phone'}
                  color={theme.primary}
                  size={24}
                  style={styles.callIcon}
                />
                <Text style={styles.phone}>{item.phone}</Text>
              </View>
              <View
                style={{
                  flexDirection: 'row',
                  marginLeft: 20,
                  justifyContent: 'flex-start',
                  alignItems: 'center',
                }}>
                <Icon
                  name={'folder'}
                  color={theme.primary}
                  size={24}
                  style={styles.balanceIcon}
                />
                <Text style={styles.balanceMember}>{item.balance}</Text>
              </View>
            </View>
          </Swipeout>
        </View>
      );
  }
  /* <View style={{flexDirection:'row',

                        marginRight:40,
                        justifyContent:'flex-end',
                        alignItems:'center'
                    }}>
                  <Icon name={"clock"}  color={theme.accentLight} size={24}
                        style={styles.callIcon}/>
                  <Text style={styles.fromNow}>{re}</Text>
              </View>*/

  _renderListDemandAdhesion() {
    if (this.state.user.category === 'hyper') {
      if (this.state.demands.length > 0) {
        return (
          <View style={{backgroundColor: '#EEEEEE', flex: 1}}>
            <FlatList
              data={this.state.demands}
              renderItem={({item}) => this._renderAddhesionItem(item)}
              refreshControl={
                <RefreshControl
                  refreshing={this.state.isRefreshing}
                  colors={[
                    theme.primary,
                    theme.purpleLight,
                    theme.reddeconnect,
                    theme.accentLight,
                  ]}
                  onRefresh={() => {
                    this.setState({isRefreshing: true});
                    listAllMembers().then(data => {
                      console.log('from refresh', data);
                      if (data !== null && data.datas) {
                        this.setState({
                          listmembers: data,
                          isLoading: false,
                          isRefreshing: false,
                        });
                      }
                    });
                  }}
                />
              }
              ListEmptyComponent={() => {
                return (
                  <View style={{flex: 1}}>
                    <View
                      style={{
                        justifyContent: 'center',
                        alignItems: 'center',
                        marginTop: 100,
                      }}>
                      <LottieView
                        style={styles.lottie}
                        source={require('./../../datas/json/629-empty-box.json')}
                        autoPlay
                        loop
                      />
                      <Text style={styles.text}>{I18n.t('NO_MEMBERS')}</Text>
                    </View>
                  </View>
                );
              }}
            />
          </View>
        );
      } else {
        return (
          <View
            style={{
              backgroundColor: 'white',
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Text>{I18n.t('NO_DEMAND_ADHESION')}</Text>
          </View>
        );
      }
    }
  }

  _renderLoadingDemandItems() {
    if (this.state.freeCodes.length > 0) {
      return (
        <View style={{backgroundColor: '#EEEEEE', flex: 1}}>
          <FlatList
            data={this.state.freeCodes}
            renderItem={({item}) => this._renderAddhesionItem(item)}
          />
        </View>
      );
    } else {
      return (
        <View
          style={{
            backgroundColor: 'white',
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text>{I18n.t('NO_GEO_POINT_CODE')}</Text>
        </View>
      );
    }
  }

  _renderAddhesionItem(item) {
    return (
      <Card
        style={{
          flex: 1,
          height: responsiveHeight(30),
          backgroundColor: 'white',
          marginBottom: 10,
        }}>
        <CardContent
          style={{
            height: responsiveHeight(20),
            flex: 1,
            justifyContent: 'space-evenly',
          }}>
          <View>
            <Text style={{marginLeft: 10}}>
              <Text style={{color: 'black'}}>{I18n.t('NAME')} :</Text>{' '}
              {item.lastname}
            </Text>
            <Text style={{marginLeft: 10}}>
              <Text style={{color: 'black'}}>{I18n.t('PHONE_NUMBER')} :</Text>{' '}
              {item.phone}
            </Text>
            <Text style={{marginLeft: 10}}>
              <Text style={{color: 'black'}}>{I18n.t('EMAIL')} :</Text>{' '}
              {item.email}
            </Text>
            <Text style={{marginLeft: 10}}>
              <Text style={{color: 'black'}}>{I18n.t('NETWORK')} :</Text>{' '}
              {item.network}
            </Text>
          </View>
        </CardContent>
        <CardAction separator={true} inColumn={false}>
          <CardButton
            title={I18n.t('ACTIVE_USER')}
            onPress={() => {
              acceptDemandAdhesion(item).then(data => {
                Alert.alert(
                  I18n.t('ACTIVATE_ACCOUNT'),
                  I18n.t('THE_ACCOUNT') +
                    ' ' +
                    item.lastname +
                    ' ' +
                    I18n.t('ACTIVATED'),
                  [
                    {
                      text: 'Ok',
                    },
                  ],
                );
                let datas = this.state.demands;
                datas.splice(datas.indexOf(item), 1);
                this.setState({demands: datas});
              });
            }}
            color={'green'}
          />
          <CardButton
            title={I18n.t('DELETE_GEOLOCATED_USER')}
            color={'red'}
            onPress={() => {}}
          />
        </CardAction>
      </Card>
    );
  }

  _renderListCodeUnused() {
    if (this.state.freeCodes.length > 0) {
      return (
        <View style={{backgroundColor: '#EEEEEE', flex: 1}}>
          <FlatList
            data={this.state.freeCodes}
            renderItem={({item}) => this._renderFreeCodeItem(item)}
          />
        </View>
      );
    } else {
      return (
        <View
          style={{
            backgroundColor: 'white',
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text>{I18n.t('NO_GEO_POINT_CODE')}</Text>
        </View>
      );
    }
  }

  _renderFreeCodeItem(item) {
    console.log(item);
    return (
      <View
        style={{
          flex: 1,
          height: responsiveHeight(30),
          backgroundColor: 'white',
          marginBottom: 10,
        }}>
        <View
          style={{
            height: responsiveHeight(20),
            flex: 1,
            justifyContent: 'space-evenly',
          }}>
          <Text style={{marginLeft: 10}}>
            <Text style={{color: 'black'}}>Contact :</Text> {item.phone}
          </Text>
          <Text style={{marginLeft: 10}}>
            <Text style={{color: 'black'}}>code Membre :</Text>{' '}
            {item.code_membre}
          </Text>
          <Text style={{marginLeft: 10}}>
            <Text style={{color: 'black'}}>code Validation :</Text>{' '}
            {item.validation_code}
          </Text>
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  circlePoint: {
    width: 50,
    height: 50,
    marginRight: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  fromNow: {
    color: theme.accentLight,
  },
  callIcon: {
    marginRight: 5,
  },
  phone: {
    textAlign: 'center',
    color: 'white',
  },
  balanceMember: {
    marginLeft: 7,
    fontSize: 18,
    fontWeight: 'bold',
    color: theme.primary,
  },
  balanceIcon: {},
  name: {
    color: 'black',
    fontSize: 20,
    margin: 20,
    fontWeight: 'bold',
  },
  surname: {
    fontSize: 17,
    marginLeft: 20,
  },
  text: {
    fontSize: 17,
    fontWeight: 'bold',
  },
  lottie: {
    width: 248,
    height: 248,
  },
})
