/* eslint-disable no-undef */
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
  Animated,
  AppState,
  ProgressBarAndroid,
  StatusBar,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {
  responsiveHeight,
  responsiveWidth,
} from 'react-native-responsive-dimensions';
import {HistoryItemSectionned, HistoryListItem} from './HistoryItem';
import {
  loadDemandeCredit,
  loadMyDemandeCredit,
} from './../../webservice/HistoryRequestApi';
import Button from 'apsl-react-native-button';
import {readUser} from '../../webservice/AuthApi';
import Calendar from 'react-native-calendario';
import I18n from 'react-native-i18n';

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 {
  accent,
  primary,
  primaryDark,
  purpleLight,
} from './../../utils/theme.json';
import {PagerTabIndicator} from 'react-native-best-viewpager';
import IconWithBadge from '../IconWithBadge';
import {Appbar, Divider, Menu, Provider} from 'react-native-paper';

var moment = require('moment-timezone');
const momentJS = require('moment');

let route = require('./../../route.json');
let theme = require('./../../utils/theme.json');

var sortIcons;
var sectionIcons;

require('./../../utils/Translations');

class MyHistory extends React.Component {
  static navigatorStyle = {
    navBarBackgroundColor: primary,
    statusBarColor: primaryDark,
    navBarTextColor: '#FFFFFF',
    navBarButtonColor: '#FFFFFF',
    contextualMenuStatusBarColor: theme.accent,
    contextualMenuBackgroundColor: theme.accentLight,
    contextualMenuButtonsColor: '#ffffff',
  };
  static navigationOptions = ({navigation}) => {
    const {routeName} = navigation.state;
    return {
      tabBarLabel:
        routeName === 'myDemand'
          ? I18n.t('MY_DEMAND')
          : I18n.t('DEMAND_RECEIVE'),
      tabBarIcon: ({focused, horizontal, tintColor}) => {
        return (
          <IconWithBadge
            badgeCount={navigation.getParam('count', 0)}
            size={20}
            name={routeName === 'myDemand' ? 'mail' : 'inbox'}
            color={focused ? tintColor : 'grey'}
          />
        );
      },

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

  constructor(props) {
    super(props, true);
    this.currentLocale = I18n.locale.includes('fr') ? 'fr' : 'en-gb';
    moment.locale(this.currentLocale);
    this.state = this.initState();
    readUser().then(user => {
      this.setState({user: user});
    });
    this._populateIcons().then(() => {});

    this.navigation = this.props.navigation;
  }

  navigationButtonPressed({buttonId}) {
    if (buttonId === 'id') {
      this.showFilter();
    } else if (buttonId === 'sectionned') {
      this.setState({isSectionned: !this.state.isSectionned});
    }
  }

  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: [],
      count: 0,
      translateAnim: new Animated.Value(0),
      visibleMenu: false,
      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) {
    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() {
    const {routeName} = this.navigation.state;
    this.setState({position: routeName === 'myDemand' ? 0 : 1});
    this.refreshData();
    /*           this.intervaller = setInterval(() => {
                       this.refreshData(false)
                  }, 2000) */
    this.animateSlidingUp(false);
    this.props.navigation.addListener('didFocus', () => {
      this.refreshData(false);
      console.warn('loading');
    });
  }


  renderOptionsMenu() {
    return (
      <View
        style={{
          position: 'absolute',
          zIndex: 100,
          paddingTop: 50,
          right: 10,
          flexDirection: 'row',
          visible: this.state.visibleMenu,
          justifyContent: 'center',
        }}>
        <Menu
          visible={this.state.visibleMenu}
          onDismiss={this._closeMenu}
          anchor={<Button onPress={this._openMenu}>Show menu</Button>}>
          {/*                    <Menu.Item onPress={() => {
                        this.setState({isSectionned: !this.state.isSectionned})
                        this._closeMenu()
                    }}
                               title="Section"/>*/}
          <Divider />
          <Menu.Item
            onPress={() => {
              this.animateSlidingUp(!this.state.isSliding);
              this._closeMenu();
            }}
            title={I18n.t('FILTER_DATE')}
          />
        </Menu>
      </View>
    );
  }

  animateSlidingUp(state = false) {
    const height = responsiveHeight(100);
    let initialValue = !state ? 0 : height,
      finalValue = !state ? height : 0;

    this.setState({isSliding: state});

    this.state.translateAnim.setValue(initialValue); //Step 3
    Animated.timing(
      //Step 4
      this.state.translateAnim,
      {
        toValue: finalValue,
        duration: 500,
        useNativeDriver: true,
      },
    ).start();
  }

  _openMenu = () => this.setState({visibleMenu: true});

  _closeMenu = () => this.setState({visibleMenu: false});

  render() {
    return (
      <Provider>
        <View style={{flex: 1}}>
          <StatusBar
            backgroundColor={theme.primaryDark}
            barStyle="light-content"
            translucent={false}
          />

          {this.renderSliding()}

          <Appbar.Header dark={true} style={{backgroundColor: theme.primary}}>
            <Appbar.BackAction
              onPress={() => {
                // resolution du proble de bug de navigation retour credit management
                this.props.navigation.push('home');
                //this.props.navigation.pop();
              }}
            />
            <Appbar.Content
              title={I18n.t('CREDIT_MANAGE')}
              subtitle={
                this.state.position === 0
                  ? I18n.t('MY_DEMAND')
                  : I18n.t('DEMAND_RECEIVE')
              }
            />
            <Appbar.Action
              icon="refresh"
              onPress={() => {
                this.refreshData();
              }}
            />
            <Appbar.Action
              icon="more-vert"
              onPress={() => {
                this._openMenu();
                this.renderSliding();
              }}
            />
          </Appbar.Header>
          {this.renderOptionsMenu()}

          {this.state.position === 0
            ? this._renderListDemandsSend()
            : this._renderListDemandReceive()}
        </View>
      </Provider>
    );
  }

  renderSliding() {
    return (
      <Animated.View
        style={[styles.slidingup, {translateY: this.state.translateAnim}]}>
        <Calendar
          onChange={range => console.log(range)}
          minDate="2018-04-20"
          startDate="2018-04-30"
          endDate="2018-05-05"
          theme={{
            activeDayColor: {},
            monthTitleTextStyle: {
              color: '#6d95da',
              fontWeight: '300',
              fontSize: 16,
            },
            emptyMonthContainerStyle: {},
            emptyMonthTextStyle: {
              fontWeight: '200',
            },
            weekColumnsContainerStyle: {},
            weekColumnStyle: {
              paddingVertical: 10,
            },
            weekColumnTextStyle: {
              color: '#b6c1cd',
              fontSize: 13,
            },
            nonTouchableDayContainerStyle: {},
            nonTouchableDayTextStyle: {},
            startDateContainerStyle: {},
            endDateContainerStyle: {},
            dayContainerStyle: {},
            dayTextStyle: {
              color: '#2d4150',
              fontWeight: '200',
              fontSize: 15,
            },
            dayOutOfRangeContainerStyle: {},
            dayOutOfRangeTextStyle: {},
            todayContainerStyle: {},
            todayTextStyle: {
              color: '#6d95da',
            },
            activeDayContainerStyle: {
              backgroundColor: '#6d95da',
            },
            activeDayTextStyle: {
              color: 'white',
            },
            nonTouchableLastMonthDayTextStyle: {},
          }}
          style={{height: responsiveHeight(60)}}
        />
        <View style={{flexDirection: 'row'}}>
          <Button>{I18n.t('QUIT')}</Button>
          <Button>{I18n.t('FILTER')}</Button>
        </View>
      </Animated.View>
    );
  }

  renderSectionnedList(list) {
    if (this.state.isLoaded) {
      let data = list;
      if (data !== null) {
        if (data.length > 0) {
          return (
            <HistoryItemSectionned
              user={this.state.user}
              list={list}
              refresh={() => this.refreshData()}
              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>
        );
      }
    }
  }

  renderList(list) {
    if (this.state.isLoaded && list instanceof Array) {
      let data = list;
      if (data !== null) {
        if (data.length > 0) {
          return (
            <HistoryListItem
              user={this.state.user}
              list={list}
              refreshing={() => {
                this.refreshData();
              }}
              refresh={() => this.refreshData()}
              isRefreshing={this.state.isRefreshing}
              navigator={this.props.navigation}
              style={styles.listbackground}
              isDemandSend={this.state.position === 0}
            />
          );
        } 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>{I18n.t('NO_ITEM_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() {
    //console.log('this.state', this.state);
    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('DEMAND_SEND'),
      },
    ];
    return (
      <PagerTabIndicator
        style={{
          height: responsiveHeight(8),
        }}
        tabs={tabs}
      />
    );
  }

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

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

  refreshData(autoref = true) {
    if (autoref) {
      this.setState({isRefreshing: true});
    }
    loadDemandeCredit()
      .then(data => {
        if (data.success !== undefined) {
          this.setState({listdata: []});
          this.updateList(data.demands);
          if (this.state.position !== 0) {
            this.props.navigation.setParams({count: data.demands.length});
          }
          this.setState({isRefreshing: false});
        }
      })
      .catch(e => {
        console.warn(e);
      });

    loadMyDemandeCredit()
      .then(data => {
        if (data.success !== undefined) {
          this.setState({listdataSend: []});
          this.setState({isRefreshing: false});
          if (this.state.position === 0) {
            this.props.navigation.setParams({count: data.demands.length});
          }

          this.updateMyList(data.demands);
        }
      })
      .catch(e => {
        console.warn(e);
      });
  }
}

export default MyHistory;
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: {
    position: 'absolute',
    height: responsiveHeight(84),
    bottom: 0,
    backgroundColor: 'white',
    width: responsiveWidth(100),
    zIndex: 1000,
  },
  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',
  },
});
