import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  TextInput,
  ScrollView,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {initialMode} from 'react-native-dark-mode';
import ImagePicker from 'react-native-image-crop-picker';
import BackHeader from '../../../components/backHeader';
import Picker from 'react-native-picker-js';
import Modal, {ModalContent} from 'react-native-modals';
import {colors} from '../../../assets/styles/colors-theme';
import history from '../../../common/history';
import NaviBar from '../../../components/navi-bar';
import Migrations from '../../../services/realm/Mirgrations';
import {Avatar} from 'react-native-elements';
import moment from 'moment';
import {inject, observer} from 'mobx-react';
import RNPickerSelect from 'react-native-picker-select';
import {Fonts} from '../../../assets/styles/fonts-theme';
import DeviceInfo from 'react-native-device-info';
import {observable} from 'mobx';
import CountryPicker, {
  getAllCountries,
} from 'react-native-country-picker-modal';
import RadioForm, {
  RadioButton,
  RadioButtonInput,
  RadioButtonLabel,
} from 'react-native-simple-radio-button';
import DateTimePicker from 'react-native-modal-datetime-picker';
import IconTextInput from '../../../components/iconTextInput';
import CommonTextInput from '../../../components/commonTextInput';
import {queryUser} from '../../../services/realm/realmManger';
import {width, height} from '../../../common/screen';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Size from '../../../common/size';

const size = new Size();

// const formatter = new Intl.NumberFormat('en-US', {
//   style: 'currency',
//   currency: 'HKD',
//   minimumFractionDigits: 0,
// });

@inject('appStore')
@observer
export default class RepresentativeContractData extends Component {
  @observable
  addAppliancesVisable = false;
  @observable
  newAppliances = {
    chineseName: '',
    englishName: '',
    value: 0,
  };
  @observable
  newKey = {
    chineseName: '',
    englishName: '',
    value: 0,
  };
  @observable
  dialogInputVisable = false;
  @observable
  DatePickervisable = false;
  @observable
  addKeyVisable = false;
  @observable
  wheelSelectData = [];
  @observable
  wheelSelected = null;
  @observable
  whichDatePicker = 0;
  @observable
  whichInput = 0;
  @observable
  apartmentData = {};
  @observable
  contractData = {
    apartmentid: '',
    apartmentAddress: '',
    signPath: '',
    representativeId: '',
    representativeName: '',
    signContractDate: null,
  };

  inputAction(action) {
    switch (action) {
      case 0:
        this.dialogInputVisable = true;
        break;

      case 1:
        this.DatePickervisable = true;
        break;
    }
  }

  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.apartmentData = this.props.navigation.state.params.apartmentData;
    console.log(this.apartmentData);
    this.init();
  }

  isDarkMode() {
    if (initialMode === 'dark') {
      this.drakMode = true;
    } else {
      this.drakMode = false;
    }
  }
  currencyFormat(num) {
    return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
  }

  init() {
    this.contractData.signContractDate = moment().toDate();

    this.contractData.apartmentAddress = this.apartmentData.address;

    // this.contractData.signContractDate = moment(
    //   this.apartmentData.signContractDate,
    //   'YYYY-MM-DD',
    // ).toDate();
    // this.contractData.endContractDate = moment(
    //   this.apartmentData.endContractDate,
    //   'YYYY-MM-DD',
    // ).toDate();

    this.contractData.id = this.apartmentData.id;
  }
  renderBackIcon() {
    return (
      <TouchableOpacity
        style={{
          position: 'absolute',
          left: 20,
          justifyContent: 'center',
          alignItems: 'center',
          height: 40,
          width: 40,
        }}
        onPress={() => {
          console.log('back');
          history.goBack(this);
        }}>
        <Icon
          name={'arrow-left'}
          size={22}
          color={'white'}
          style={{
            ...Platform.select({
              ios: {},
              android: {
                //top: 40,
              },
            }),
          }}
        />
      </TouchableOpacity>
    );
  }

  componentWillMount() {
    this.isDarkMode();
  }

  componentDidMount() {}

  dateStringHandler(date) {
    if (date === null) {
      return '';
    } else {
      return (
        date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear()
      );
    }
  }

  removeRemark(index) {
    this.contractData.remark.splice(index, 1);
  }

  handleDatePicked = date => {
    this.DatePickervisable = false;
    console.log('A date has been picked: ', date);
    // this.hideDateTimePicker();
    var momentDate = moment(date);
    momentDate = momentDate.second(0);
    momentDate = momentDate.minute(0);
    momentDate = momentDate.hour(12);
    this.contractData.signContractDate = momentDate.toDate();
  };

  //   contractDatePicker(title, which, dateData) {
  //     return (
  //       <View
  //         style={{
  //           flexDirection: 'row',
  //           width: width,
  //           paddingTop: 10,
  //           alignItems: 'center',
  //         }}>
  //         <Text style={{marginLeft: 10, marginRight: 10}}>{title}</Text>
  //         <Text style={{marginRight: 10}}>
  //           {this.dateStringHandler(dateData)}
  //         </Text>
  //         <Icon
  //           size={30}
  //           name={'calendar-alt'}
  //           onPress={() => {
  //             this.DatePickervisable = true;
  //             this.whichDatePicker = which;
  //           }}
  //         />
  //       </View>
  //     );
  //   }

  async editAction() {
    await this.store.saveEdit(this.props.navigation.state.params.index);
    await this.store.resetApartmentData();
    await this.store.getUser();
    history.goBack(this);
  }

  deleteAction() {
    Alert.alert(
      '',
      'Are you sure?',
      [
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        {
          text: 'Yes',
          onPress: () => {
            this.deleteApartment();
          },
        },
      ],
      {cancelable: false},
    );
  }

  async deleteApartment() {
    await this.store.deleteApartment(this.props.navigation.state.params.index);
    await this.store.resetApartmentData();
    await this.store.getUser();
    history.goBack(this);
  }
  whichNotificationIndex() {
    if (this.whichNotificationPicker === 0) {
      return this.apartmentData.rentNotification;
    } else {
      return this.apartmentData.endContractNotification;
    }
  }
  notificationSelectAction(index) {
    if (this.whichNotificationPicker === 0) {
      console.log(index);
      this.apartmentData.rentNotification = index;
    } else {
      this.apartmentData.endContractNotification = index;
    }
  }

  alertAction(msg) {
    Alert.alert(
      'Error',
      msg,
      [{text: 'OK', onPress: () => console.log('ok')}],
      {cancelable: false},
    );
  }

  renderButton() {
    if (this.props.navigation.state.params.create) {
      return (
        <View style={{width: width, alignItems: 'center'}}>
          <TouchableOpacity
            onPress={() => {
              this.nextAction(true);
            }}
            style={{
              marginTop: 50,
              marginBottom: 20,
              backgroundColor: colors.mainColor,
              width: width - 60,
              height: 60,
              borderRadius: 10,
              shadowColor: '#000',
              justifyContent: 'center',
              alignItems: 'center',
              shadowOffset: {
                width: 0,
                height: 2,
              },
              shadowOpacity: 0.23,
              shadowRadius: 2.62,

              elevation: 4,
            }}>
            <Text
              style={{color: 'white', fontFamily: Fonts.ubuntu, fontSize: 18}}>
              {this.store.text.next}
            </Text>
          </TouchableOpacity>
        </View>
      );
    } else {
      return (
        <View style={{width: width, alignItems: 'center'}}>
          <TouchableOpacity
            onPress={() => {
              this.nextAction(false);
            }}
            style={{
              marginTop: 50,
              marginBottom: 20,
              backgroundColor: colors.mainColor,
              width: width - 60,
              height: 60,
              borderRadius: 10,
              shadowColor: '#000',
              justifyContent: 'center',
              alignItems: 'center',
              shadowOffset: {
                width: 0,
                height: 2,
              },
              shadowOpacity: 0.23,
              shadowRadius: 2.62,

              elevation: 4,
            }}>
            <Text
              style={{color: 'white', fontFamily: Fonts.ubuntu, fontSize: 18}}>
              Save
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              this.deleteAction();
            }}
            style={{
              marginTop: 10,
              marginBottom: 20,
              backgroundColor: colors.mainColor,
              width: width - 60,
              height: 60,
              borderRadius: 10,
              shadowColor: '#000',
              justifyContent: 'center',
              alignItems: 'center',
              shadowOffset: {
                width: 0,
                height: 2,
              },
              shadowOpacity: 0.23,
              shadowRadius: 2.62,

              elevation: 4,
            }}>
            <Text
              style={{color: 'white', fontFamily: Fonts.ubuntu, fontSize: 18}}>
              Delete
            </Text>
          </TouchableOpacity>
        </View>
      );
    }
  }
  nextAction(nextOrEdit) {
    let data = this.apartmentData;
    if (data.name !== null) {
      if (data.address !== null) {
        if (data.signContractDate !== null) {
          if (data.endContractDate !== null) {
            if (data.rent !== null) {
              if (nextOrEdit) {
                history.push(this, '/uploadImage', {create: true});
              } else {
                this.editAction();
              }
            } else {
              var msg = 'Please input ' + this.store.text.rent;
              this.alertAction(msg);
            }
          } else {
            var msg = 'Please input ' + this.store.text.contractExpiryDate;
            this.alertAction(msg);
          }
        } else {
          var msg = 'Please input ' + this.store.text.dateOfContract;
          this.alertAction(msg);
        }
      } else {
        var msg = 'Please input ' + this.store.text.address;
        this.alertAction(msg);
      }
    } else {
      var msg = 'Please input ' + this.store.text.apartment;
      this.alertAction(msg);
    }
  }

  showDatetimePicker() {
    console.log('App started in', initialMode, 'mode');
    var color = 'white';
    if (initialMode === 'dark') {
      color = 'black';
    }
    if (this.DatePickervisable) {
      return (
        <View style={{backgroundColor: color}}>
          <DateTimePicker
            value={this.whichDate()}
            mode="date"
            is24Hour={true}
            display="default"
            onChange={this.handleDatePicked}
          />
        </View>
      );
    } else {
      return null;
    }
  }

  async clickAction(action) {
    switch (action) {
      case 'contractDate':
        this.DatePickervisable = true;
        break;
      case 'payDay':
        this.wheelSelectData = [];
        for (var i = 1; i <= 28; i++) {
          this.wheelSelectData.push(i);
        }
        this.wheelSelected = 'payDay';
        this.picker.toggle();
        break;
      case 'rentFreePeriod':
        this.wheelSelectData = [];
        for (var i = 0; i <= 90; i++) {
          this.wheelSelectData.push(i);
        }
        this.wheelSelected = 'rentFreePeriod';
        this.picker.toggle();
        break;
      case 'noteLeasebackMonth':
        this.wheelSelectData = [];
        for (var i = 1; i <= 12; i++) {
          this.wheelSelectData.push(i);
        }
        this.wheelSelected = 'noteLeasebackMonth';
        this.picker.toggle();
        break;

      case 'monthOfpaymentInLieuOfNotice':
        this.wheelSelectData = [];
        for (var i = 1; i <= 12; i++) {
          this.wheelSelectData.push(i);
        }
        this.wheelSelected = 'monthOfpaymentInLieuOfNotice';
        this.picker.toggle();
        break;
      case 'atleastRentOfmonth':
        this.wheelSelectData = [];
        for (var i = 1; i <= 36; i++) {
          this.wheelSelectData.push(i);
        }
        this.wheelSelected = 'atleastRentOfmonth';
        this.picker.toggle();
        break;
      case 'whoPayManagementFee':
        this.wheelSelectData = ['業主 Landlord', '租客 Tenant'];

        this.wheelSelected = 'whoPayManagementFee';
        this.picker.toggle();
        break;

      case 'whoPayGovernemtRate':
        this.wheelSelectData = ['業主 Landlord', '租客 Tenant'];
        this.wheelSelected = 'whoPayGovernemtRate';
        this.picker.toggle();
        break;
      case 'whoPayGovernmentRent':
        this.wheelSelectData = ['業主 Landlord', '租客 Tenant'];
        this.wheelSelected = 'whoPayGovernmentRent';
        this.picker.toggle();
        break;
    }
  }

  charSelectedHandler(char, which) {
    if (which) {
      if (char == 'owner') {
        return '業主 Landlord';
      } else {
        return '租客 Tenant';
      }
    } else {
      if (char == '業主 Landlord') {
        return 'owner';
      } else {
        return 'tenant';
      }
    }
  }

  appliancesSelecterColorsReturn(value, which) {
    switch (which) {
      case 'sub':
        if (value == 0) {
          return colors.line2Color;
        } else {
          return 'black';
        }
        break;
      case 'add':
        if (value <= 19) {
          return 'black';
        } else {
          return colors.line2Color;
        }
        break;
      case 'buttonBackground':
        if (value > 0) {
          return colors.mainColor;
        } else {
          return 'white';
        }
        break;
    }
  }

  renderList(which, action, title, content) {
    if (which) {
      return (
        <TouchableOpacity
          style={styles.inputTextView}
          onPress={() => {
            this.clickAction(action);
          }}>
          <Text style={styles.inputTextTitleView}>{title}</Text>

          <View style={{flexDirection: 'row', marginBottom: 5}}>
            <View style={{flex: 0.8}}>
              <Text
                style={{
                  fontSize: 20,
                  color: 'black',
                  fontFamily: Fonts.ubuntuTh,
                }}>
                {content}
              </Text>
            </View>
            <View style={{flex: 0.2, alignItems: 'flex-end'}}>
              <Icon
                name="chevron-down"
                color={'black'}
                size={20}
                style={{marginRight: 10}}
              />
            </View>
          </View>
        </TouchableOpacity>
      );
    } else {
      return <View></View>;
    }
  }

  completeClickAcion() {
    console.log(this.contractData);
    history.push(this, '/newLease', {
      contractData: this.contractData,
      showSign: true,
    });
  }

  appliancesClickAction() {
    this.addAppliancesVisable = false;
    this.contractData.appliances.push(this.newAppliances);
  }

  keyClickAction() {
    this.addKeyVisable = false;
    this.contractData.key.push(this.newKey);
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <View
          style={{
            width: width,
            height: Platform.OS === 'ios' ? 65 : 80,
            backgroundColor: colors.mainColor,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Text
            style={{fontFamily: Fonts.ubuntu, color: 'white', fontSize: 20}}>
            {this.store.text.add + this.store.text.addContract}
          </Text>
          {this.renderBackIcon()}

          <TouchableOpacity
            onPress={() => {
              this.completeClickAcion();
            }}
            style={{
              position: 'absolute',
              right: 20,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Text
              style={{
                fontFamily: Fonts.ubuntu,
                fontSize: 17,
                color: 'white',
              }}>
              {this.store.text.complete}
            </Text>
          </TouchableOpacity>
        </View>
        <KeyboardAwareScrollView style={{flex: 1}}>
          <View style={{marginLeft: 20, marginRight: 20}}>
            <Text style={styles.title}>{'基本資料'}</Text>

            {this.renderList(
              true,
              'contractDate',
              this.store.text.dateOfContract,
              moment(this.contractData.signContractDate).format('DD/MM/YYYY'),
            )}

            <View style={styles.inputTextView}>
              <Text style={styles.inputTextTitleView}>
                {this.store.text.representativeId}
              </Text>

              <View style={{flexDirection: 'row', marginBottom: 5}}>
                <View style={{flex: 0.8}}>
                  <Text
                    style={{
                      fontSize: 20,
                      color: 'black',
                      fontFamily: Fonts.ubuntuTh,
                    }}>
                    {this.apartmentData.leaseMonth + this.store.text.months}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </KeyboardAwareScrollView>
        <DateTimePicker
          value={this.contractData.signContractDate}
          mode={'date'}
          isVisible={this.DatePickervisable}
          onConfirm={this.handleDatePicked}
          isDarkModeEnabled={this.drakMode}
          onCancel={() => {
            this.DatePickervisable = false;
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  button: {
    marginTop: 20,
    width: width,
    height: 60,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  inputTextView: {
    marginTop: 20,
    borderBottomWidth: 1,
    borderBottomColor: colors.line2Color,
    height: 50,
  },
  inputTextTitleView: {
    fontFamily: Fonts.ubuntuL,
    fontSize: 14,
    color: colors.line2Color,
  },
  title: {
    fontFamily: Fonts.ubuntu,
    fontSize: 17,
    marginTop: 20,
  },
  subtitle: {
    fontFamily: Fonts.ubuntu,
    fontSize: 14,
  },
  buttonText: {
    color: '#fff',
  },
  picker: {
    fontSize: 20,
    paddingVertical: 12,
    paddingHorizontal: 10,
    borderWidth: 1,
    borderColor: 'black',
    borderRadius: 4,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
  textView: {
    color: colors.mainColor,
    fontFamily: Fonts.ubuntu,
    fontSize: size.getSize(20),
    fontWeight: 'bold',
  },
});
const pickerSelectStyles = StyleSheet.create({
  inputIOS: {
    fontSize: 16,
    paddingVertical: 12,
    paddingHorizontal: 10,
    borderWidth: 1,
    borderColor: 'gray',
    borderRadius: 4,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
  inputAndroid: {
    fontSize: 16,
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderWidth: 0.5,
    borderColor: 'black',
    borderRadius: 8,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
});
