/* eslint-disable prettier/prettier */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Platform, StyleSheet, AppState, FlatList, ProgressBarAndroid, TouchableOpacity, Text, View } from 'react-native';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { responsiveFontSize, responsiveHeight, responsiveWidth } from 'react-native-responsive-dimensions';
import { HistoryListItem, HistoryItemSectionned } from './HistoryItem';
import { credrequester } from './../../route.json';
import { loadDemandeCredit, loadMyDemandeCredit } from './../../webservice/HistoryRequestApi';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import BaseScreen from './../../screens/BaseScreen'
import Button from 'apsl-react-native-button'
import { readUser } from "../../webservice/AuthApi";

let route = require('./../../route.json')
let moment = require('moment-timezone')
let theme = require('./../../utils/theme.json')
import { primary, primaryDark, accent, purpleLight, primaryLight } from './../../utils/theme.json';
import { IndicatorViewPager, PagerTabIndicator } from 'react-native-best-viewpager';
type Props = {};
var sortIcons;
var sectionIcons;
import I18n from 'react-native-i18n'
import { IlinkEmitter } from "../../utils/events";
require('./../../utils/Translations')
import { SinglePickerMaterialDialog } from 'react-native-material-dialog';
import { Header } from "react-native-elements";
import { withNavigationFocus } from "react-navigation";
class History extends BaseScreen {
     static navigatorStyle = {
          navBarBackgroundColor: primary,
          statusBarColor: primaryDark,
          navBarTextColor: '#FFFFFF',
          navBarButtonColor: '#FFFFFF',
          contextualMenuStatusBarColor: theme.accent,
          contextualMenuBackgroundColor: theme.accentLight,
          contextualMenuButtonsColor: '#ffffff',

  };
     static navigationOptions = ({ navigation }) => {
          return {
               title: I18n.t('CREDIT_MANAGE'),
               drawerLabel: navigation.getParam('name', I18n.t('CREDIT_MANAGE')),
               drawerIcon: ({ tintColor }) => (
                    <Icon
                         name={'credit-card'}
                         size={24}
                    />
               ),
          }
     };

     static options(passProps) {
          return {
               topBar: {
                    visible: true,
                    drawBehind: false,
                    background: {
                         color: theme.primaryDark,
                    },
               },
          }
     }

     constructor(props) {
          super(props, true);
          this.state = this.initState();
          readUser().then((user) => { this.setState({ user: user }) })
          this._populateIcons().then(() => {
          });
          IlinkEmitter.on("langueChange", this.updateLangue.bind(this))
          this.refreshData();
     };

     navigationButtonPressed({ buttonId }) {
          if (buttonId === 'id') {
               this.showFilter();
          } else if (buttonId === 'sectionned') {
               this.setState({ isSectionned: !this.state.isSectionned })
          }
     }
     updateLangue() {
          this.props.navigation.setParams({ name: I18n.t('CREDIT_MANAGE') })
          this.forceUpdate()
     }
     onNavigatorEvent(event) {
          if (event.type === 'NavBarButtonPress') {
               if (event.id === 'id') {
                    this.showFilter();
               } else if (event.id === 'sectionned') {
                    this.setState({ isSectionned: !this.state.isSectionned })
               }
          } else {
               switch (event.id) {
                    case 'willAppear':
                         this.refreshData()
                         break;
                    case 'didAppear':
                         break;
                    case 'willDisappear':
                         break;
                    case 'didDisappear':
                         break;
                    case 'willCommitPreview':
                         break;
               }
          }
     }

     showFilter() {

          /*if (this.state.filter) {
              Navigation.mergeOptions(route.stackRoot,
                  {
                  topBar: {
                      rightButtons: [
                          {
                              title: 'Non Traité',
                          },
                          {
                              title: 'Traité',
                          },
                          {
                              title: 'Période',
                          },
                          {
                              title: 'Tout',
                          },
                          {
                              title: 'Trier par',
                          },
                          {
                              title: '',
                          },
                      ],
                      onButtonPressed: (index) => {
                          let data = this.state.conserve
                          console.log(index)
                          console.log(data);
  
                          if (data !== null) {
                              let filtre = "";
                              if (index < 2) {
                                  switch (index) {
                                      case 0:
                                          filtre = I18n.t('NO_TREAT')
                                          break;
                                      case 1:
                                          filtre = I18n.t('TREAT');
                                          break;
  
                                  }
                                  let fi = data.filter(item => item.statut === filtre)
                                  this.setState({listdata: fi, filter: true})
                              } else if (index === 2) {
                                  this.setState({panelVisible: true})
                              } else {
                                  this.setState({listdata: data, filter: false})
                              }
                          }
                      }
                  }}
              );
  
          } else {
              Navigation.mergeOptions(route.stackRoot,
                  {
                      topBar: {
                          rightButtons: [
                              {
                                  title: I18n.t('NO_TREAT'),
                              },
                              {
                                  title: I18n.t('TREAT'),
                              }
                              , {
                                  title: I18n.t('PERIOD'),
                              },
                              {
                                  title: '',
                              },
                              {
                                  title: 'Trier par',
                              }, {
                                  title: '',
                              },
                          ],
                          onButtonPressed: (index) => {
                              let data = this.state.conserve
                              if (data != null && data.length > 0) {
                                  var filtre = "";
                                  if (index < 2) {
                                      switch (index) {
                                          case 0:
                                              filtre = I18n.t('NO_TREATED');
                                              break;
                                          case 1:
                                              filtre = I18n.t('TREATED');
                                              break;
  
                                      }
                                      let fi = data.filter(item => item.statut === filtre)
                                      this.setState({listdata: fi, filter: true})
                                  } else if (index === 2) {
                                      this.setState({panelVisible: true})
                                      this.props.navigator.showContextualMenu(
                                          {
                                              rightButtons: [
                                                  {
                                                      title: I18n.t('CANCEL'),
                                                  },
                                                  {
                                                      title: I18n.t('FILTER'),
                                                  },
  
                                              ],
                                              onButtonPressed: (index) => {
                                                  console.log(index)
  
                                                  switch (index) {
                                                      case 1:
                                                          let {dateend, datestart} = this.state;
                                                          this.onfilterPress();
                                                  }
                                                  this.setState({panelVisible: false});
                                              }
                                          }
                                      );
                                  } else {
                                      this.setState({listdata: data, filter: false})
                                  }
                              }
                          }
                      }
                  }
              );
  
          }*/
     }

     _populateIcons = function () {
          return new Promise(function (resolve, reject) {
               Promise.all(
                    [
                         Icon.getImageSource('sort', 30),
                         Icon.getImageSource('layer-group', 30),
                    ]
               ).then((values) => {
                    sortIcons = values[0];
                    sectionIcons = values[1];
                    resolve(true);
               }).catch((error) => {
                    console.log(error);
                    reject(error);
               }).done();
          });
     };

     initState() {
          return {
               user: {},
               listdata: [],
               listdataSend: [],
               conserve: [],
               appState: AppState.currentState,
               filter: false,
               sortIcons: null,
               panelVisible: false,
               filder_disable: true,
               datestartformated: 'La date de debut',
               dateendformated: 'La date de fin',
               datestart: null,
               dateend: null,
               isLoaded: false,
               isSectionned: false,
               isDateTimePickerVisible: false,
               isDateEndTimePickerVisible: false,
          }
     }

     updateList(data: Array) {
          if (!this.state.filter) {
               let rev = data.reverse()
               this.setState({ listdata: rev, conserve: rev, isLoaded: true });
          }
     }
     updateMyList(data) {
          if (!this.state.filter) {
               let rev = data.reverse()
               this.setState({ listdataSend: rev, conserve: rev, isLoaded: true });
          }

     }
     componentDidMount() {
          AppState.addEventListener('change', this._handleAppStateChange);
     }

     componentWillUnmount() {
          AppState.removeEventListener('change', this._handleAppStateChange);

     }
     _handleAppStateChange = (nextAppState) => {
          if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
          }
          this.setState({ appState: nextAppState });
     }
     renderList(list: Array) {
          if (this.state.isLoaded) {
               let data = list;
               if (data !== null) {
                    if (data.length > 0) {
                         return (<HistoryListItem
                              list={list}
                              refreshing={() => { this.refreshData() }}
                              isRefreshing={this.state.isRefreshing}
                              navigator={this.props.navigation}
                              style={styles.listbackground} />)
                    } else if (this.state.filter) {

                         return (
                              <View style={styles.emptyListe}>
                                   <Text>{I18n.t('NO_ITEM_REQUEST')}</Text>
                              </View>
                         )
                    } else if (data.length === 0) {
                         return (
                              <View style={styles.emptyListe}>
                                   <Text>{I18n.t('NO_ITEM_REQUEST')}</Text>
                              </View>
                         )
                    } else {
                         return (
                              <View style={styles.emptyListe}>
                                   <ProgressBarAndroid />
                                   <Text>{I18n.t('LOADING_DOTS')}</Text>
                              </View>
                         )
                    }
               } else {
                    return (
                         <View style={styles.emptyListe}>
                              <Text>{I18n.t('EMPTY_LIST_REQUEST')} </Text>
                         </View>
                    )

               }

          } else if (list.length === 0) {
               return (
                    <View style={styles.emptyListe}>
                         <Text>Aucuns éléments ne corresponds</Text>
                    </View>
               )
          }

     }
     componentDidUpdate(prevProps) {
          if (prevProps.isFocused !== this.props.isFocused && this.props.isFocused) {
               this.refreshData()
          }
     }

     render() {

          return (
               <View style={{ flex: 1, marginBottom: 20 }}
               >

                    <IndicatorViewPager
                         style={{ flex: 1 }}
                         indicator={
                              this.state.user.category === "geolocated" ? this._renderTabGeolocated() :
                                   this.state.user.category === 'hyper' ? this._renderTabHyper()
                                        : this._renderTabs()}
                    >
                         {this.state.user.category !== "hyper" ? this._renderListDemandsSend() : null}
                         {this.state.user.category !== "geolocated" ? this._renderListDemandReceive() : null}
                    </IndicatorViewPager>
               </View>
          );

     }
     renderSectionnedList(list) {

          if (this.state.isLoaded) {
               let data = list;
               if (data !== null) {
                    if (data.length > 0) {
                         return (<HistoryItemSectionned
                              list={list}
                              navigator={this.props.navigator}
                              style={styles.listbackground} />)
                    } else if (this.state.filter) {

                         return (
                              <View style={styles.emptyListe}>
                                   <Text>{I18n.t('NO_ITEMS_REQUEST')}</Text>
                              </View>
                         )
                    } else {
                         return (
                              <View style={styles.emptyListe}>
                                   <ProgressBarAndroid />
                                   <Text>{I18n.t('LOADING_DOTS')}</Text>
                              </View>
                         )
                    }
               } else {
                    return (
                         <View style={styles.emptyListe}>
                              <Text>{I18n.t('EMPTY_LIST_REQUEST')}</Text>
                         </View>
                    )

               }
          }
     }
     renderLoading() {
          return (<View><ProgressBarAndroid /><Text>{I18n.t('LOADING_DOTS')}</Text></View>)
     }
     showSlidingUpPanel() {
          /*  return (<SlidingUpPanel
                style={styles.slidingup}
                height={responsiveHeight(100)}
                visible={this.state.panelVisible}
                ref={(c) => this.panel = c}
                draggableRange={{top: responsiveHeight(100), bottom: 0}}
                onRequestClose={() => this.setState({panelVisible: false})}>
                <View style={styles.container}>
                    {this.showSlidingUpView()}
                </View>
            </SlidingUpPanel>)
        }
    
        showSlidingUpView() {
          /*  return (
                <View style={datefilter.container}>
                    <View stlye={datefilter.content}>
                     <DatepickerRange
                            styles={{
                                borderColor: 'transparent',
                                borderRadius: 0,
                                margin: 10,
                                height:responsiveWidth(50)
                            }}
                            initialMonth='201801'
                            onSelect={(fromdate,untildate)=>this._handleDatePicked(fromdate,untildate)}
                            dayHeadings={['D', 'L', 'M', 'M', 'J', 'V', 'S']}
                             maxMonth={12}
                            startdate={moment('20180101').format('YYYYMMDD')}
                            untilDate='20181231'
                            minDate='20180101'
                            maxDate='20181231'
                             buttonColor='green'
                            showReset={false}
                    showClose={false}
                    placeHolderStart= 'Date de debut'
                    placeHolderUntil= 'Date fin'
                    selectedBackgroundColor= 'green'
                    selectedTextColor='white'
                        />
                </View>
                </View>
    
                    )*/
     }

     onfilterPress() {
          let { datestart, dateend } = this.state;
          let data = this.state.conserve;

          if (data !== null) {
               data = data.filter(item => {
                    let mda = moment(item.dateAjout)
                    return moment(item.dateAjout).isAfter(moment(datestart).toDate()) && (mda.isBefore(moment(dateend).toDate()))
               })

               this.setState({ listdata: data, panelVisible: false, filter: true })
          }

     }

     _showDateTimePicker = (type) => {
          if (type === 1)
               this.setState({
                    isDateTimePickerVisible: true,
               });
          else this.setState({
               isDateEndTimePickerVisible: true,
          });
     }
     _showDateEndPicker = () => this.setState({ isDateEndTimePickerVisible: true });

     _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false, isDateEndTimePickerVisible: false });
     _handleDatePicked = (fromdate, enddate) => {
          console.log([fromdate, enddate]);

          this.setState({
               datestart: fromdate,
               datestartformated: moment(fromdate).format('dddd Do ,MMMM YYYY'),
               dateend: enddate,
               dateendformated: moment(enddate).format('dddd Do ,MMMM YYYY'),
          });
          let startdate = this.state.datestart;
          let enddatemo = moment(enddate);
          let dif = moment(enddatemo).diff(startdate);
          if (dif < 0) {
               this.setState({ filder_disable: true });
               this.props.navigator.showSnackbar({
                    text: I18n.t('DATE_WRONG'),
                    duration: 'long',
                    backgroundColor: 'red',
                    textColor: 'white',
               })
          } else {
               this.setState({ filder_disable: false });
          }

          this._hideDateTimePicker();
     };

     printOptions() {
          if (this.state.user.category === "hyper") {
               return (<ActionButton buttonColor={accent}>
                    <ActionButton.Item buttonColor={purpleLight} title={I18n.t('SAVE_HISTORY')} onPress={() => {

                    }}>
                         <Icon name="save" style={styles.actionButtonIcon} />
                    </ActionButton.Item>
               </ActionButton>);
          } else {
               return (<ActionButton buttonColor={accent}>
                    <ActionButton.Item buttonColor={primary} title={I18n.t('MAKE_REQUEST')}
                         onPress={() => {
                              this.props.navigation.push(route.credrequester, {
                                   onGoBack: () => this.refreshData(),
                              })
                         }}
                    >
                         <Icon name="edit" style={styles.actionButtonIcon} />
                    </ActionButton.Item>
                    <ActionButton.Item buttonColor={purpleLight} title={I18n.t('SAVE_HISTORY')} onPress={() => {

                    }}>
                         <Icon name="save" style={styles.actionButtonIcon} />
                    </ActionButton.Item>
               </ActionButton>)
          }
     }

     _renderListDemandsSend() {
          return (<View style={styles.container}>
               {
                    this.state.isLoaded ?
                         this.state.isSectionned ?
                              this.renderSectionnedList(this.state.listdataSend) :
                              this.renderList(this.state.listdataSend) : this.renderLoading()
               }
               {this.printOptions()}
               {this.showSlidingUpPanel()}
          </View>
          )
     }

     _renderListDemandReceive() {
          return (<View style={styles.container}>
               {
                    this.state.isLoaded ?
                         this.state.isSectionned ?
                              this.renderSectionnedList(this.state.listdata) :
                              this.renderList(this.state.listdata) : this.renderLoading()
               }
               {this.printOptions()}
               {this.showSlidingUpPanel()}
          </View>
          )
     }

     _renderTabGeolocated() {
          let tabs = [{
               text: I18n.t('DEMANDE_SEND'),
          }]
          return <PagerTabIndicator
               style={{
                    height: responsiveHeight(8),
               }}
               tabs={tabs} />;
     }

     _renderTabHyper() {
          let tabs = [{
               text: I18n.t('DEMANDE_RECEIVE'),
          }]
          return <PagerTabIndicator
               style={{
                    height: responsiveHeight(8),
               }}
               tabs={tabs} />;
     }

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


     refreshData() {
          this.setState({ isRefreshing: true })
          loadDemandeCredit().then((data) => {
               if (data.success !== undefined) {
                    this.updateList(data.demands);
                    this.setState({ isRefreshing: false })
               }
          });
          loadMyDemandeCredit().then((data) => {
               if (data.success !== undefined) {
                    this.setState({ isRefreshing: false })
                    this.updateMyList(data.demands)
               }
          })
     }
}
export default withNavigationFocus(History);
const datefilter = StyleSheet.create({
     titleHeader: {
          fontSize: 20,
          fontWeight: 'bold',
          color: 'black',
          flex: 1,
     },
     datetitle: {
          fontSize: 17,
          color: 'black',
          marginLeft: responsiveWidth(2),
     },
     datetext: {
          fontSize: 16,
          marginLeft: responsiveWidth(5),
     },
     content: {
          flex: 2,

     },
     btnContainer: {
          flexDirection: 'row',
          width: responsiveWidth(100),
          alignSelf: 'flex-end',
          flex: 2,
     },
     btn: {
          flex: 1,
          borderColor: 'transparent',
          borderRadius: 0,
     },
     btntext: {
          fontWeight: 'bold',
          color: accent,
     },
     container: {
          flex: 1,
          justifyContent: 'space-evenly',
     },
})
const styles = StyleSheet.create({
     slidingup: {
          width: responsiveHeight(100),
     },
     root: {
          flex: 1,
     },
     container: {
          flex: 1,
          backgroundColor: 'white',
          justifyContent: 'center',
          alignItems: 'center',
     },
     emptylist: {
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
     },
     backgroundd_drawer: {
          backgroundColor: '#000',
     },
     listbackground: {
     },
     actionButtonIcon: {
          fontSize: 20,
          height: 22,
          color: 'white',
     },
     welcome: {
          fontSize: 20,
          textAlign: 'center',
          margin: 10,
     },
     instructions: {
          textAlign: 'center',
          color: '#333333',
          marginBottom: 5,
     },
     dateText: {
          marginTop: 20,
          marginLeft: responsiveWidth(13),
          marginBottom: 20,
          fontSize: 17,
     },
     titlecontent: {
          fontSize: 17,
          marginLeft: responsiveWidth(10),

          color: 'black',
     },
     content: {
          flex: 8,
     },

     title: {
          fontSize: 20,
          marginLeft: 20,
          marginTop: 20,
          color: 'black',
          fontWeight: 'bold',
     },
});
