/**
 * Profile Settings页面
 * @邠心vbe on 2021/04/27
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, ScrollView, Switch, Pressable } from 'react-native';
import apiUser from '../../api/apiUser';
import { host } from '../../api/http';
import Button, { ElevationObject } from '../../components/Button';
import Dialog from '../../components/Dialog';
import { StationBack } from '../../components/Toolbar';
import ProfileBackground from '../../icons/ProfileBackground';
import TopChargeBackground from '../../icons/TopChargeBackground';
import utils from '../../utils/utils';
import { PageList } from '../Router';
import VehicleList from './VehicleList';
export default class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: {
        notifyLowBalance: true,
        notifyChargingComplete: true,
        notifyPromotionsOffers: true
      },
      refreshId: 0,
      totalVehicle: 0
    };
    this.changed = false;
  }

  componentDidMount() {
    this.props.navigation.addListener('focus', () => {
      getUserInfo(info => {
        this.setState({
          userInfo: info,
          refreshId: this.state.refreshId + 1
        });
      }, true);
    });
  }

  componentWillUnmount() {
    if (this.changed) {
      this.setChangedSwitch();
    }
  }

  removeVehicle(id) {
    Dialog.showDialog({
      title: 'Remove Vehicle',
      message: 'Are you sure you want to remove this vehicle?',
      callback: btn => {
        if (btn == 'ok') {
          Dialog.dismissLoading();
          this.deleteVehicle(id);
        }
      }
    })
  }

  deleteVehicle(id) {
    Dialog.showProgressDialog();
    apiUser.deleteVehicle({
      vehiclePk: id
    }).then(res => {
      Dialog.dismissLoading();
      toastShort('Delete successfully');
      this.setState({
        refreshId: this.state.refreshId + 1
      })
    }).catch(err => {
      Dialog.dismissLoading();
      toastShort(err);
    });
  }

  changeSwitch(key, value) {
    userInfo[key] = value;
    this.setState({
      userInfo: userInfo
    });
    this.changed = true;
  }

  setChangedSwitch() {
    apiUser.setNotifySwitch(userInfo);
  }

  deleteAccount() {
    Dialog.showDialog({
      title: 'Delete My Account',
      message: 'Are you sure you want to delete your account? This operation cannot be revoke.',
      ok: 'CONFIRM',
      callback: button => {
        if (button == Dialog.BUTTON_OK) {
          this.deleteMyAccount();
        }
      }
    })
  }

  deleteMyAccount() {
    Dialog.showProgressDialog();
    apiUser.deleteAccount().then(res => {
      toastShort('Successfully deleted!')
      Dialog.dismissLoading();
      setTimeout(() => {
        startPage(PageList.login);
      }, 500);
    }).catch(err => {
      Dialog.dismissLoading();
      toastShort(err)
    })
  }

  render() {
    return (
      <ScrollView style={styles.container}>
        {/* Profile Info */}
        <View style={styles.headerView}>
          <View style={styles.background}>
            {/* <ProfileBackground/> */}
          </View>
          {/* <Image
            style={styles.background}
            source={require('../../images/user/bg-profile.svg')}/> */}
          <Pressable
            style={styles.profileView}
            onPress={() => {
              startPage(PageList.editProfile);
            }}>
            { userInfo.photoUrl
            ? <Image
                style={styles.avatar}
                source={{uri: host + userInfo.photoUrl}}/>
            : <Image
                style={styles.avatar}
                source={require('../../images/user/icon-default.jpg')}/>
            }
            <View style={styles.infoContent}>
              <Text
                style={styles.nickname}
                ellipsizeMode='tail'
                numberOfLines={1}>{userInfo.nickName}</Text>
              <Text style={styles.userText}>{userInfo.email}</Text>
              <Text style={styles.userText}>{(utils.isNotEmpty(userInfo.callingCode) && "+" + userInfo.callingCode) + userInfo.phone}</Text>
            </View>
            <FontAwesome
              size={34}
              color='#333'
              name='angle-right'/>
          </Pressable>
          <StationBack bottom={52} scale={0.8}/>
        </View>
        {/* Summary Info */}
        <View style={styles.cardView}>
          <View style={styles.cardItem}>
            <Image
              style={styles.cardIcon}
              source={require('../../images/user/card-vehicle.png')}/>
            <View style={styles.cardInfo}>
              <Text style={styles.cardPrimary}>{this.state.totalVehicle}</Text>
              <Text style={styles.cardLabel}>My Vehicles</Text>
            </View>
          </View>
          <View style={[styles.cardItem, styles.cardDivide]}>
            <Image
              style={styles.cardIcon}
              source={require('../../images/user/card-wallet.png')}/>
            <Pressable
              style={styles.cardInfo}
              onPress={() => {
                startPage(PageList.wallet);
              }}>
              <Text style={styles.cardPrimary}>{currency}{userInfo.credit}</Text>
              <Text style={styles.cardLabel}>Credits</Text>
            </Pressable>
          </View>
        </View>
        {/* Vehicle List */}
        <View style={styles.titleView}>
          <Text style={styles.title}>My Vehicles</Text>
          <Button
            style={{backgroundColor: '#fff'}}
            borderRadius={3}
            viewStyle={styles.titleAdd}
            onClick={() => {
              startPage(PageList.addVehicle)
            }}>
            <Entypo name='plus' size={14} color='#333'/>
            <Text style={{fontSize: 12, paddingLeft: 1, color: '#333'}}>Add Vehicle</Text>
          </Button>
        </View>
        <View style={styles.verhicleList}>
          <VehicleList
            refreshId={this.state.refreshId}
            onResult={count => {
              this.setState({
                totalVehicle: count
              })
            }}
            onDelete={id => this.removeVehicle(id)}
          />
        </View>
        {/* Account List */}
        {/* <View style={styles.titleView}>
          <Text style={styles.title}>My Cards</Text>
          <Button
            textColor='#333'
            style={styles.titleAdd}
            onClick={() => {
              startPage(PageList.addCard)
            }}>
            <Entypo name='plus' size={14} color='#333'/>
            <Text style={{fontSize: 12, paddingLeft: 1}}>Add Card</Text>
          </Button>
        </View>
        <View style={styles.accountList}>
          <CardList refreshId={this.state.refreshId}/>
        </View> */}
        {/* Notifications */}
        <View style={styles.titleView}>
          <Text style={styles.title}>Notifications</Text>
        </View>
        <View style={styles.notificationView}>
          <Pressable
            style={styles.notificationItem}
            android_ripple={ripple}
            onPress={() => {
              this.changeSwitch("notifyChargingComplete", !userInfo.notifyChargingComplete);
            }}>
            <Text style={styles.notiLabel}>Notify me when charging complete</Text>
            <Switch
              value={this.state.userInfo.notifyChargingComplete}
              trackColor={isIOS ? { false: "#B2B2B2", true: colorAccent } : null}
              onValueChange={v => {
                this.changeSwitch("notifyChargingComplete", v);
              }}/>
          </Pressable>
          <Pressable
            style={[styles.notificationItem, styles.divide]}
            android_ripple={ripple}
            onPress={() => {
              this.changeSwitch("notifyLowBalance", !userInfo.notifyLowBalance);
            }}>
            <Text style={styles.notiLabel}>Notify me when credits is low balance</Text>
            <Switch 
              value={this.state.userInfo.notifyLowBalance}
              trackColor={isIOS ? { false: "#B2B2B2", true: colorAccent } : null}
              onValueChange={v => {
                this.changeSwitch("notifyLowBalance", v);
              }}/>
          </Pressable>
          <Pressable
            style={[styles.notificationItem, styles.divide]}
            android_ripple={ripple}
            onPress={() => {
              this.changeSwitch("notifyPromotionsOffers", !userInfo.notifyPromotionsOffers);
            }}>
            <Text style={styles.notiLabel}>Notify me for promotions and offers</Text>
            <Switch
              value={this.state.userInfo.notifyPromotionsOffers}
              trackColor={isIOS ? { false: "#B2B2B2", true: colorAccent } : null}
              onValueChange={v => {
                this.changeSwitch("notifyPromotionsOffers", v);
              }}/>
          </Pressable>
        </View>
        <Button
          style={styles.deleteButton}
          text="DELETE MY ACCOUNT"
          textColor="#fff"
          onClick={() => this.deleteAccount()}
        />
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  headerView: {
    paddingBottom: 72
  },
  background: {
    left: 0,
    right: 0,
    bottom: 0,
    height: $vw(62.4),
    alignItems: 'center',
    position: 'absolute'
  },
  profileView: {
    padding: 16,
    zIndex: 10,
    alignItems: 'center',
    flexDirection: 'row'
  },
  avatar: {
    width: 66,
    height: 66,
    borderWidth: 2,
    borderRadius: 80,
    borderColor: '#fff'
  },
  infoContent: {
    flex: 1,
    paddingLeft: 16,
  },
  nickname: {
    color: '#000',
    fontSize: 16,
    paddingTop: 1,
    paddingBottom: 1.5,
  },
  userText: {
    color: '#333',
    fontSize: 13,
    paddingTop: 1.5
  },
  cardView: {
    padding: 16,
    marginTop: -56,
    marginLeft: 16,
    marginRight: 16,
    borderRadius: 10,
    ...ElevationObject(2),
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: 'white',
  },
  cardItem: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center'
  },
  cardDivide: {
    borderLeftWidth: 1,
    borderLeftColor: '#EEE'
  },
  cardIcon: {
    width: 32,
    height: 32
  },
  cardInfo: {
    paddingLeft: 16,
    alignItems: 'center'
  },
  cardPrimary: {
    color: '#333',
    fontSize: 18,
    paddingBottom: 2
  },
  cardLabel: {
    color: '#333',
    fontSize: 13,
  },
  titleView: {
    padding: 12,
    alignItems: 'center',
    flexDirection: 'row'
  },
  title: {
    flex: 1,
    padding: 8,
    color: '#000',
    fontSize: 16,
  },
  titleAdd: {
    padding: 8,
    color: '#333',
    alignItems: 'center',
    flexDirection: 'row'
  },
  verhicleList: {
    paddingLeft: 16,
    paddingRight: 16,
    marginBottom: -16
  },
  accountList: {
    paddingLeft: 16,
    paddingRight: 16,
    marginBottom: -16
  },
  notificationView: {
    marginLeft: 16,
    marginRight: 16,
    marginBottom: 20,
    borderRadius: 10,
    overflow: 'hidden',
    paddingLeft: 16,
    paddingRight: 16,
    borderColor: '#f5f5f5',
    borderWidth: 1,
    backgroundColor: 'white',
    ...ElevationObject(1.5)
  },
  notificationItem: {
    paddingTop: 16,
    paddingBottom: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  notiLabel: {
    flex: 1,
    color: '#333',
    fontSize: 14
  },
  divide: {
    borderTopWidth: 1,
    borderTopColor: '#eee'
  },
  deleteButton: {
    ...$margin(32, 16, 16),
    backgroundColor: '#EA0A2A'
  }
})
