/* eslint-disable react/jsx-no-duplicate-props */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable no-unused-vars */
import React, {PureComponent} from 'react';
import {
  FlatList,
  RefreshControl,
  SectionList,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  responsiveFontSize,
  responsiveWidth,
} from 'react-native-responsive-dimensions';
import Icon from 'react-native-vector-icons/FontAwesome5';
import I18n from 'react-native-i18n';

import 'moment/locale/fr';
import 'moment/locale/es-us';
import 'moment/locale/en-au';
import 'moment/locale/en-gb';
import 'moment/locale/en-ca';
import 'moment/locale/en-ie';
import 'moment/locale/en-il';
import 'moment/locale/en-nz';
import {Color} from '../../config/Color';

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

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

export class HistoryItem extends React.Component {
  constructor(props) {
    super(props);
    this.currentLocale = I18n.locale.includes('fr') ? 'fr' : 'en-gb';
    console.log('Current Locale item', this.currentLocale);
    moment.locale(this.currentLocale);
    this.state = this.initState();
  }

  statusLabel = status => {
    switch (status) {
      case '0':
        return I18n.t('NO_TREAT');
      case '1':
        return I18n.t('TREAT');
      case '2':
        return I18n.t('REFUSED');
    }
  };

  colorLabel = status => {
    switch (status) {
      case '0':
        return Color.accentColor;
      case '1':
        return Color.greenColor;
      case '2':
        return Color.redColor;
    }
  };

  descriptionLabelUserType = user => {
    let textDescription =
      this.props.selfData.montant +
      ' ' +
      I18n.t('TO_') +
      ' ' +
      this.props.selfData.reseau;

    switch (user.category) {
      case 'geolocated':
        return `${I18n.t('DEMAND_TEXT_FIRST_PART_YOU')} ${textDescription}`;
      case 'super':
        return this.props.isDemandSend
          ? `${I18n.t('DEMAND_TEXT_FIRST_PART_YOU')} ${textDescription}`
          : `${I18n.t('THE_AGENT')} ${this.props.selfData.lastname} (${
              this.props.selfData.phone
            }) ${I18n.t('DEMAND_TEXT_FIRST_PART')} ${textDescription}`;

      case 'hyper':
        return `${I18n.t('THE_SUPERVISOR')} ${this.props.selfData.lastname} (${
          this.props.selfData.phone
        }) ${I18n.t('DEMAND_TEXT_FIRST_PART')} ${textDescription}`;
    }
  };

  initState() {
    var textTitle = ' Transaction ' + this.props.selfData.id;
    var textDescription =
      I18n.t('PHONE') +
      ' ' +
      this.props.selfData.phone +
      ' ' +
      I18n.t('DEMAND_TEXT_FIRST_PART') +
      ' ' +
      this.props.selfData.montant +
      ' ' +
      I18n.t('TO_') +
      ' ';
    textDescription += this.props.selfData.reseau;
    var today = new Date();
    var l = this.props.selfData.date_creation;
    let t = this.props.selfData.status;
    var re = moment
      .tz(this.props.selfData.date_creation, moment.tz.guess())
      .format();
    re = moment(re);
    return {
      title: textTitle,
      description: this.descriptionLabelUserType(this.props.user),
      status: this.statusLabel(this.props.selfData.status),
      time: re.fromNow(),
      navigator: this.props.navigator,
      type: t,
      colorstate: this.colorLabel(t),
    };
  }

  render() {
    //console.log("ITEM RENDER", this.props.selfData)
    return (
      <TouchableOpacity
        onPress={() =>
          this.props.navigator.navigate(route.historyItemDetails, {
            item: this.props.selfData,
            onGoBack: () => this.props.refresh(),
          })
        }>
        <View style={style.content}>
          <Text style={style.title}>{this.state.title}</Text>
          <Text style={style.description}>{this.state.description}</Text>
          <View style={style.timeContent}>
            <Text
              style={{
                fontWeight: 'bold',
                marginLeft: 20,
                marginBottom: 10,
                color: this.state.colorstate,
              }}>
              {this.statusLabel(this.props.selfData.status)}
            </Text>
            <Text style={style.time}>{this.state.time}</Text>
          </View>
          <View style={style.bottomSeparator} />
        </View>
      </TouchableOpacity>
    );
  }
}

export class HistoryItemSectionned extends PureComponent {
  _keyExtractor = (item, index) => item.id;
  _renderItem = ({item}) => (
    <HistoryItem navigator={this.props.navigator} selfData={item} />
  );

  constructor(props) {
    super(props);
    this.state = this.initState();
    this.currentLocale = I18n.locale.includes('fr') ? 'fr' : 'en-gb';
    moment.locale(this.currentLocale);
  }

  render() {
    return (
      <SectionList
        sections={[
          {
            title: 'Demande traité',
            type: 0,
            data: this.state.treat,
            size: this.state.conservetreat.length,
            expandState: this.state.istreatexpand,
          },
          {
            title: 'Demande non traité',
            type: 1,
            data: this.state.untreat,
            size: this.state.conserveuntreat.length,
            expandState: this.state.isuntreatexpand,
          },
        ]}
        renderSectionHeader={({
          section: {title, type, data, size, expandState},
        }) => (
          <TouchableOpacity
            onPress={() => this.onPressedHeader(type)}
            style={{
              backgroundColor: theme.accent,
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'row',
              flex: 1,
              height: 70,
              width: responsiveWidth(100),
            }}>
            <View
              style={{
                height: 70,
                justifyContent: 'center',
                flex: 1,
                width: responsiveWidth(100),
              }}>
              <Text
                style={{
                  fontWeight: 'bold',
                  marginLeft: 20,
                  fontSize: 20,
                  color: 'white',
                }}>
                {title}
              </Text>
              <Text
                style={{
                  fontWeight: 'bold',
                  marginLeft: 20,
                  fontSize: 16,
                  color: 'white',
                }}>
                {size} demande(s)
              </Text>
            </View>
            <Icon
              name={expandState ? 'sort-up' : 'sort-down'}
              size={30}
              color={'white'}
              style={{marginRight: 20}}
            />
          </TouchableOpacity>
        )}
        style={style.listStyle}
        extraData={this.state}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
      />
    );
  }

  onPressedHeader(type) {
    if (type === 0) {
      this.setState({
        istreatexpand: !this.state.istreatexpand,
        treat: this.state.istreatexpand ? [] : this.state.conservetreat,
      });
    } else {
      this.setState({
        isuntreatexpand: !this.state.isuntreatexpand,
        untreat: this.state.isuntreatexpand ? [] : this.state.conserveuntreat,
      });
    }
  }

  initState() {
    let data = this.props.list;

    return {
      conservetreat: data.filter(item => item.statut === I18n.t('TREAT')),
      treat: data.filter(item => item.statut === I18n.t('TREAT')),
      istreatexpand: true,
      conserveuntreat: data.filter(item => item.statut !== I18n.t('TREAT')),
      untreat: data.filter(item => item.statut !== I18n.t('TREAT')),
      isuntreatexpand: true,
    };
  }
}

export class HistoryListItem extends React.Component {
  _keyExtractor = (item, index) => item.id;

  _onPressItem = id => {};
  _renderItem = ({item}) => {
    //console.log('ITEM ', item);
    return (
      <HistoryItem
        isDemandSend={this.props.isDemandSend}
        user={this.props.user}
        refresh={this.props.refresh}
        navigator={this.props.navigator}
        selfData={item}
      />
    );
  };

  constructor(props) {
    super(props);
    this.state = this.initState();
    this.currentLocale = I18n.locale.includes('fr') ? 'fr' : 'en-gb';
    moment.locale(this.currentLocale);
  }

  initState() {
    return {
      refreshing: false,
    };
  }

  render() {
    return (
      <FlatList
        style={style.listStyle}
        data={this.props.list}
        extraData={this.state}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
        refreshControl={
          <RefreshControl
            refreshing={this.props.isRefreshing}
            colors={[
              theme.primary,
              theme.purpleLight,
              theme.reddeconnect,
              theme.accentLight,
            ]}
            onRefresh={this.props.refreshing}
          />
        }
      />
    );
  }

  _onRefresh() {
    this.setState({refreshing: true});
    setTimeout(() => {
      this.setState({refreshing: false});
    }, 5000);
  }
}

const style = StyleSheet.create({
  content: {
    width: responsiveWidth(100),
    borderBottomColor: '#FFFFFF',
    flex: 1,
    flexDirection: 'column',
    paddingTop: 10,
  },
  listStyle: {
    backgroundColor: 'white',
  },
  bottomSeparator: {
    width: responsiveWidth(100),
    height: 5,
    justifyContent: 'center',
    alignSelf: 'center',
    backgroundColor: '#EEE',
  },
  title: {
    color: '#000',
    paddingLeft: 10,
    fontSize: responsiveFontSize(2.2),
  },
  description: {
    fontSize: responsiveFontSize(1.8),
    color: '#4f5b62',
    paddingLeft: 10,
  },
  timeContent: {
    justifyContent: 'space-between',
    flex: 1,
    marginTop: 10,
    marginBottom: 5,
    flexDirection: 'row',
  },
  time: {
    fontWeight: 'bold',
    marginRight: 20,
    marginBottom: 10,
    color: theme.accent,
  },
  treat: {},
});
