/* eslint-disable no-unused-vars */
/* eslint-disable no-shadow */
/* eslint-disable react-native/no-inline-styles */
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
  Alert,
  AsyncStorage,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import {
  responsiveFontSize,
  responsiveHeight,
  responsiveWidth,
} from 'react-native-responsive-dimensions';
import {primary, primaryDarkAdvanced} from './../../utils/theme.json';
import {disconnect, readUser} from './../../webservice/AuthApi';
import I18n from 'react-native-i18n';
import Button from 'apsl-react-native-button';
import {IlinkEmitter} from './../../utils/events';
import {SafeAreaView} from 'react-navigation';
import DeviceInfo from 'react-native-device-info';
import Configuration from '../../webservice/persistences/Configuration';
import {ScrollView} from 'react-native-gesture-handler';

const route = require('./../../route.json');
require('./../../utils/Translations');
var DBEvents = require('react-native-db-models').DBEvents;
let theme = require('./../../utils/theme.json');

export default class OptionsMenu extends Component {
  static navigatorStyle = {
    statusBarColor: primaryDarkAdvanced,
  };
  commandeListe;

  constructor(props) {
    super(props);
    this.state = this.initState();
    IlinkEmitter.on('menuLink', this.onMenuNavigationEvent.bind(this));
    IlinkEmitter.on('userconnect', this.onUserConnect.bind(this));
    IlinkEmitter.on('userdisconnect', this.hideSideMenu.bind(this));
    IlinkEmitter.on('langueChange', this.updateLangue.bind(this));
    this.configuration = new Configuration();
    readUser().then(user => {
      if (user !== null && user !== undefined) {
        this.setState({user});
      }
    });
  }

  retrieveAndroidInformation() {
    this.configuration
      ._getData()
      .then(lang => {
        if (lang) {
          I18n.locale = lang;
          readUser().then(result => {
            setTimeout(() => {
              this.updateUser(result);
            }, 3000);
          });
        } else {
          let code = DeviceInfo.getDeviceLocale();
          I18n.locale = code.toLowerCase();
          readUser()
            .then(result => {
              setTimeout(() => {
                this.updateUser(result);
              }, 3000);
            })
            .catch(e => {
              this.props.navigation.navigate('Auth');
            });
        }
      })
      .catch(e => {
        let code = DeviceInfo.getDeviceLocale();
        I18n.locale = code.toLowerCase();
        readUser()
          .then(result => {
            setTimeout(() => {
              this.updateUser(result);
            }, 3000);
          })
          .catch(e => {
            this.props.navigation.navigate('Auth');
          });
      });

    return '';
  }

  componentDidMount() {
    const items = this.props.navigation.router.childRouters.sta.childRouters;
    this.setState({items: items});
    this.retrieveAndroidInformation();
  }

  updateLangue() {
    this.setState({lang: 'change'});
    this.forceUpdate();
  }

  componentWillUnmount() {}

  onMenuNavigationEvent(menuOption) {
    /* Navigation.mergeOptions(this.props.componentId,{
             sideMenu: {
                 left: {
                     visible: false,
                 }
             }
         })
        switch (menuOption){
             case "home":{
                 this.setState({currentId:0})
             }
                 break;
             case "userInfo":{
                 this.setState({currentId:1})
             }
         }*/
  }

  onUserConnect() {
    readUser().then(user => {
      if (user !== null && user !== undefined) {
        this.updateUser(user);
      }
    });
  }

  onNavigatorEvent(event) {}

  hideSideMenu() {
    /*  Navigation.mergeOptions("drawer", {
              sideMenu: {
                  left: {
                      visible: false,
                      enabled:false
                  }
              }
          });*/
  }

  initState() {
    return {
      user: null,
      menu: [],
      currentId: 0,
    };
  }

  getGeolocatedUserMenu() {
    return [
      {title: I18n.t('MAP'), id: 0, key: 0, icon: 'md-map', active: true},
      {
        title: I18n.t('MY_ACCOUNT'),
        id: 1,
        key: 1,
        icon: 'md-person',
        active: false,
      },
      {
        title: I18n.t('WALLET'),
        id: 6,
        key: 6,
        icon: 'md-wallet-outline',
        active: false,
      },
      {
        title: I18n.t('CREDIT_MANAGE'),
        id: 2,
        key: 2,
        icon: 'md-card',
        active: false,
      },
      {
        title: I18n.t('ADD_NETWORK'),
        id: 11,
        key: 11,
        icon: 'md-people',
        active: false,
      },
      {
        title: I18n.t('CHANGE_INFORMATION'),
        id: 13,
        key: 13,
        icon: 'md-person',
        active: false,
      },
      {
        title: I18n.t('NOTIFICATIONS'),
        id: 3,
        key: 3,
        icon: 'md-notifications',
        active: false,
      },
      {
        title: I18n.t('CONFIGURATIONS'),
        id: 4,
        icon: 'md-settings',
        active: false,
      },
    ];
  }

  getSuperUserMenu() {
    return [
      {title: I18n.t('MAP'), id: 0, key: 0, icon: 'md-map', active: true},
      {
        title: I18n.t('MY_ACCOUNT'),
        id: 1,
        key: 1,
        icon: 'md-person',
        active: false,
      },
      {
        title: I18n.t('WALLET'),
        id: 6,
        key: 6,
        icon: 'md-wallet-outline',
        active: false,
      },
      {
        title: I18n.t('CREDIT_MANAGE'),
        id: 2,
        key: 2,
        icon: 'md-card',
        active: false,
      },
      {
        title: I18n.t('GROUP_MANAGE'),
        id: 5,
        key: 5,
        icon: 'md-people',
        active: false,
      },
      {
        title: I18n.t('NOTIFICATIONS'),
        id: 3,
        key: 3,
        icon: 'md-notifications',
        active: false,
      },
      {
        title: I18n.t('CONFIGURATIONS'),
        id: 4,
        icon: 'md-settings',
        active: false,
      },
    ];
  }

  getHyperUsermenu() {
    return [
      {title: I18n.t('MAP'), id: 0, key: 0, icon: 'md-map', active: true},
      {
        title: I18n.t('MY_ACCOUNT'),
        id: 1,
        key: 1,
        icon: 'md-person',
        active: false,
      },
      {
        title: I18n.t('WALLET'),
        id: 6,
        key: 6,
        icon: 'md-wallet-outline',
        active: false,
      },
      {
        title: I18n.t('CREDIT_MANAGE'),
        id: 2,
        key: 2,
        icon: 'md-card',
        active: false,
      },
      {
        title: I18n.t('GROUP_MANAGE'),
        id: 5,
        key: 5,
        icon: 'md-people',
        active: false,
      },
      {
        title: I18n.t('NOTIFICATIONS'),
        id: 3,
        key: 3,
        icon: 'md-notifications',
        active: false,
      },
      {
        title: I18n.t('CONFIGURATIONS'),
        id: 4,
        icon: 'md-settings',
        active: false,
      },
    ];
  }

  updateUser(user) {
    let menu = [];
    if (user !== undefined) {
      console.log('USER', user.category);
      /*  Navigation.mergeOptions("drawer", {
                  sideMenu: {
                      left: {
                          visible: false,
                          enabled:true
                      }
                  }
              });*/
      if (user.category !== undefined) {
        switch (user.category) {
          case 'geolocated':
            menu = this.getGeolocatedUserMenu();
            break;
          case 'super':
            menu = this.getSuperUserMenu();
            break;
          case 'hyper':
            menu = this.getHyperUsermenu();
            break;
        }
      } else {
        menu = this.getUserMenu();
      }
    }

    this.setState({user: user, menu: menu});
  }

  getUserMenu() {
    return [
      {
        title: I18n.t('MAP'),
        id: 0,
        key: 0,
        icon: 'md-map',
        active: true,
      },
      {
        title: I18n.t('MY_ACCOUNT'),
        id: 1,
        key: 1,
        icon: 'md-person',
        active: false,
      },
      {
        title: I18n.t('WALLET'),
        id: 6,
        key: 6,
        icon: 'md-wallet-outline',
        active: false,
      },
      {
        title: I18n.t('NOTIFICATIONS'),
        id: 3,
        key: 3,
        icon: 'md-notifications',
        active: false,
      },
      {
        title: I18n.t('CONFIGURATIONS'),
        id: 4,
        icon: 'md-settings',
        active: false,
      },
    ];
  }

  redirectToScreen = item => {
    console.log('Item Menu Click', item);

    if (this.state.user === null) {
      return;
    } else {
      switch (this.state.user.category) {
        case 'super':
          if (item === 'walletSelect') {
            item = 'walletDetail';
          }
          this.props.navigation.navigate(item, {
            agentId: this.state.user.agentId,
          });

          break;
        case 'hyper':
          if (item === 'walletSelect') {
            item = 'walletDetail';
          }
          this.props.navigation.navigate(item, {
            agentId: this.state.user.agentId,
          });

          break;
        case 'geolocated':
          this.props.navigation.navigate(item);
          break;

        default:
          if (item === 'walletSelect') {
            item = 'walletDetailUser';
          }
          this.props.navigation.navigate(item, {userId: this.state.user.id});

          break;
      }
    }
  };
  _renderItem = (item, key) => {
    if (
      item === 'creditrequest' ||
      item === 'historyItemDetails' ||
      item === 'filter' ||
      item === 'networks' ||
      item === 'walletDetail' ||
      item === 'walletDetailUser' ||
      item === 'walletDepot' ||
      item === 'walletRetrait' ||
      item === 'createIdentification' ||
      item === 'walletOptionSelect' ||
      item === 'validateIdentification' ||
      item === 'createIdentificationUser' ||
      item === 'operateurOptionSelect' ||
      item === 'paiementFacture' ||
      item === 'envoieWalletToWalletUser' ||
      item === 'envoieWalletToCashUser' ||
      item === 'linkCard' ||
      item === 'envoieWalletToCardUser' ||
      item === 'envoieWalletToBankUser' ||
      item === 'retraitWalletVersCashUser' ||
      item === 'retraitCarteVersWalletUser' ||
      item === 'retraitEnCashAgent' ||
      item === 'retraitCarteVersCashAgent' ||
      item === 'retraitCarteVersAutreWalletUser' ||
      item === 'modal' ||
      item === 'autreCarte' ||
      item === 'carteLier' ||
      item === 'paymentCard' ||
      item === 'autreCarteN' ||
      item === 'carteLierN' ||
      item === 'walletNanosante' ||
      item === 'mobileMoneyNanoSante' ||
      item === 'envoieCashVersWalletAgent' ||
      item === 'envoieCashVersAutreWalletAgent' ||
      item === 'retraitCarteVersCashUser' ||
      item === 'envoiCashVersCashAgent' ||
      item === 'envoieCashVersCashAgent' ||
      item === 'envoieCashVersCarteAgent' ||
      item === 'modifyIdentificationUser' ||
      item === 'createGroupNanoCredit' ||
      item === 'groupNanoCredit' ||
      item === 'demandeValidationGroupe' ||
      item === 'adhererGroupNanoCredit' ||
      item === 'myNanoCreditGroup' ||
      item === 'askNanoCredit' ||
      item === 'refundNanoCreditUser' ||
      item === 'cautionNanoCreditAgent' ||
      item === 'epargnerArgentUser' ||
      item === 'askNanoCredit' ||
      item === 'casserEpargneUser' ||
      item === 'envoieWalletToBankAgent' ||
      item === 'reattachAccountUser' ||
      item === 'insuranceSubscriptionScreen' ||
      item === 'addBeneficiaryScreen' ||
      item === 'activateBuySubscriptionScreen' ||
      item === 'saisirFeuilleSoinScreen' ||
      item === 'validateConsultationScreen' ||
      item === 'validateConsultationDetailScreen' ||
      item === 'executerPrescriptionScreen' ||
      item === 'modifierFeuilleSoinScreen' ||
      item === 'modifierExecutionPrescriptionScreen' ||
      item === 'historiqueNanoSanteUserScreen' ||
      item === 'demandeAutorisationSoinScreen' ||
      item === 'deleteBeneficiaryScreen' ||
      item === 'StopSubscriptionScreen' ||
      item === 'stopSubscriptionScreen' ||
      item === 'renewAssuranceScreen' ||
      item === 'webviewScreen' ||
      item === 'historiqueNanoSanteAgentScreen' ||
      item === 'historiqueNanoSanteSuperHyperScreen' ||
      item === 'PDFViewerScreen' ||
      item === 'ubaFormScreen'
    ) {
      return null;
    } else {
      const color = this.state.currentId === item.id ? theme.accent : 'grey';
      //console.log("ITEM OPTION MENU", item);
      return (
        <TouchableOpacity
          key={key}
          onPress={() => {
            this.props.navigation.toggleDrawer();
            this.setState({currentId: item.id});
            this.redirectToScreen(item);
          }}>
          <View style={items.content}>
            <Icon name={this.getIcon(item)} size={32} />
            <Text
              style={{
                marginLeft: 20,
                fontSize: 16,
              }}>
              {this.getNameItems(item)}
            </Text>
          </View>
        </TouchableOpacity>
      );
    }
  };
  _onPress = item => {
    this.setState({currentId: item.id});
    let current = this.state.menu.filter(item => {
      return item.active;
    })[0];
    current.active = false;
    item.active = true;
    let newMenu = [];
    this.state.menu.forEach(function (it) {
      if (it.id === current.id) {
        newMenu.push(current);
      } else if (it.id === item.id) {
        newMenu.push(item);
      } else {
        newMenu.push(it);
      }
    });
    this.setState({menu: newMenu});
    /*    switch(item.id){
                case 2:
                   Navigation.push(route.stackRoot,{
                     component: {
                         name: histo,
                     },
                       options: {
                           topBar: {
                               title: {
                                   text: I18n.t('CREDIT_MANAGE')
                               }
                           }
                       }
               });
                 break;
                case 0:
                    Navigation.popToRoot(route.stackRoot)
                   IlinkEmitter.emit("menuLink","home");
                break;
                case 1:
                    Navigation.push(route.stackRoot,{
                        component: {
                            name:useraccount,
           },
                        options: {
                            sideMenu:{
                                visibility:false
                            },
                            topBar: {
                                title: {
                                    text:I18n.t('MY_ACCOUNT')
                                },
                                hideOnScroll: true,

                            }
                        }
                    });
                    IlinkEmitter.emit("menuLink","userInfo");
                   break;
               case 3:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:notification,
                       },
                       options: {
                           topBar: {
                               title: {
                                   text:I18n.t('NOTIFICATION')

                               }
                           }
                       }
                   });
                   IlinkEmitter.emit("menuLink","notification");

                   break;
               case 4:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:configurations,
                       },
                       options: {
                           topBar: {
                               title: {
                                   text:I18n.t('CONFIGURATIONS')

                               }
                           }
                       }
                   });
                   IlinkEmitter.emit("menuLink","config");
                   break;
               case 5:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:route.superviseurgroup,
                       },
                       options: {
                           topBar: {
                               title: {
                                   text:I18n.t('GROUP_MANAGE')

                               }
                           }
                       }
                   });
                   IlinkEmitter.emit("menuLink","manage_group");

                   break;
               case 7:     Navigation.push(route.stackRoot,{
                   component: {
                       name:route.credrequester,
                   },
                   options: {
                       topBar: {
                         visible:false
                       }
                   }
               });
                   break;
               case 11:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:route.addNetwork,
                       },
                       options: {
                           topBar: {
                               visible:false
                           }
                       }
                   });
                   break;
               case 12:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:route.generateNetwork,
                       },
                       options: {
                           topBar: {
                               visible:false
                           }
                       }
                   });
                   break;
               case 13:
                   Navigation.push(route.stackRoot,{
                       component: {
                           name:route.updateinfo,
                       },
                       options: {
                           topBar: {
                               visible:false
                           }
                       }
                   });
           };
             Navigation.mergeOptions(this.props.componentId,{
                 sideMenu: {
                     left: {
                         visible: false,
                     }
                 }
             })
      */
  };

  getNameItems(item) {
    let icon = item;
    switch (item) {
      case 'home':
        icon = I18n.t('MAP');
        break;
      case 'useraccount':
        icon = I18n.t('MY_ACCOUNT');
        break;
      case 'walletSelect':
        icon = I18n.t('WALLET');
        break;
      case 'Historique':
        icon = I18n.t('CREDIT_MANAGE');
        break;
      case 'superviseurgroup':
        icon = I18n.t('GROUP_MANAGE');
        break;
      case 'updateinformation':
        icon = I18n.t('CHANGE_INFORMATION');
        break;
      case 'notificationview':
        icon = I18n.t('NOTIFICATIONS');
        break;
      case 'configuration':
        icon = I18n.t('CONFIGURATIONS');
        break;
      case 'addNetwork':
        icon = I18n.t('ADD_NETWORK');
        break;
      case 'about':
        icon = I18n.t('ABOUT');
        break;
    }
    return icon;
  }

  getIcon(item) {
    let icon = 'md-map';
    switch (item) {
      case 'home':
        icon = 'md-map';
        break;
      case 'useraccount':
        icon = 'md-person';
        break;
      case 'walletSelect':
        icon = 'md-wallet';
        break;
      case 'Historique':
        icon = 'md-card';
        break;
      case 'superviseurgroup':
        icon = 'md-people';
        break;
      case 'notificationview':
        icon = 'md-notifications';
        break;
      case 'updateinformation':
        icon = 'md-people';
        break;
      case 'configuration':
        icon = 'md-settings';
        break;
      case 'addNetwork':
        icon = 'md-people';
        break;
      case 'about':
        icon = 'md-contacts';
        break;
      case 'ubaFormScreen':
        icon = 'md-person-add';
        break;
    }
    return icon;
  }

  render() {
    var name = this.state.user ? this.state.user.firstname : '';
    const surname = this.state.user ? this.state.user.lastname : '';
    if (!this.state.lang && this.state.lang !== 'change') {
      return (
        <View style={styles.container}>
          <View style={styles.headercontent}>
            <Text style={styles.headerTitle}>{name}</Text>
            <Text style={styles.headerTitle}>{surname}</Text>
            <Text style={styles.headerPhone}>
              {this.state.user ? '' + this.state.user.phone : ''}
            </Text>
          </View>
          <ScrollView
            style={{
              flex: 1,
              height: responsiveHeight(40),
            }}>
            <SafeAreaView forceInset={{top: 'always', horizontal: 'never'}}>
              {this.state.items &&
                Object.keys(this.state.items).map((item, key) => {
                  return  this._renderItem(item, key);
                })}
            </SafeAreaView>
          </ScrollView>
          <Button
            textStyle={styles.btntext}
            style={styles.btnDeconnect}
            onPress={() => this.userDeconnect()}>
            {I18n.t('DISCONNEXION')}
          </Button>
        </View>
      );
    } else {
      setTimeout(() => this.setState({lang: ''}), 500);
      return <View />;
    }
  }

  userDeconnect() {
    Alert.alert(
      I18n.t('DISCONNEXION'),
      I18n.t('DISCONNEXION_TEXT'),
      [
        {},
        {
          text: I18n.t('NO'),
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: I18n.t('YES'),
          onPress: () => {
            disconnect().then(() => {
              IlinkEmitter.emit('userdisconnect');
              AsyncStorage.removeItem('@config:onesignalIds');
              this.props.navigation.navigate('Auth');
            });
          },
        },
      ],
      {cancelable: false},
    );
  }

  watchUser() {
    readUser().then(user => {
      if (user !== null && user !== undefined) {
        if (user.id !== this.state.user.id) {
          this.updateUser(user);
        }
      }
    });
  }
}

const items = StyleSheet.create({
  content: {
    width: responsiveWidth(100),
    height: 50,
    paddingLeft: 20,
    flexDirection: 'row',
    alignItems: 'center',
  },
  itemText: {
    color: '#000000',
    marginLeft: 20,
    fontSize: responsiveFontSize(2),
  },
});
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  btnDeconnect: {
    borderColor: 'transparent',
    marginLeft: 20,
    marginRight: 20,
    backgroundColor: theme.accent,
  },
  btntext: {
    color: 'white',
    fontSize: 17,
    fontWeight: 'bold',
  },
  headerTitle: {
    fontSize: 14,
    marginBottom: 5,
    color: 'white',
    fontWeight: 'bold',
  },
  headerPhone: {
    fontSize: 12,
    marginBottom: 20,
    color: 'white',
    justifyContent: 'flex-end',
  },
  listMenu: {
    paddingTop: 15,
  },
  headercontent: {
    height: responsiveHeight(30),
    backgroundColor: primary,
    justifyContent: 'flex-end',
    alignItems: 'flex-start',
    paddingLeft: 20,
  },
  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,
  },
});
