import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Image,
  Share,
  Alert,
} from 'react-native';
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Modal, {ModalContent} from 'react-native-modals';
import LoadingView from '../../common/loading';
import Switch from 'react-native-switch-pro';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
var _ = require('lodash');
import Realm from 'realm';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import history from '../../common/history';
import NaviBar from '../../components/navi-bar';
import Migrations from '../../services/realm/Mirgrations';
import BackHeader from '../../components/backHeader';
import {inject, observer} from 'mobx-react';
import {observable} from 'mobx';
import {queryUser} from '../../services/realm/realmManger';
import AsyncStorageHelper from '../../common/asyncStorageHelper';
import ImagePicker from 'react-native-image-crop-picker';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import {width, height} from '../../common/screen';
const asyncStorageHelper = new AsyncStorageHelper();

let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});

@inject('appStore')
@observer
export default class AddTenant extends Component {
  @observable
  AddTenantSwitch: false;

  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  componentDidMount() {}

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

  list(title, contents, color) {
    return (
      <View
        style={{
          flexDirection: 'row',
          marginRight: 5,
          marginLeft: 5,
          marginTop: 10,
          width: scale(265),
        }}>
        <View style={{}}>
          <Text style={{fontFamily: Fonts.ubuntu, color: colors.textColor}}>
            {title + ':    '}
          </Text>
        </View>
        <View style={{}}>
          <Text style={{fontFamily: Fonts.ubuntu, color: color}}>
            {contents}
          </Text>
        </View>
      </View>
    );
  }

  async getUserApartmentData() {
    let user = queryUser();
    return user;
  }

  async saveAction() {
    await this.store.deleteDemo();
    var data = this.store.apartmentData;
    let user = realm.objects('User');
    await this.store.rentlocalNotificationHandler();
    await this.store.endContractlocalNotificationHandler();
    try {
      let newApartment = {
        id: this.store.idGenerator(),
        createDate: new Date(),
        modifyDate: new Date(),
        name: data.name,
        address: data.address,
        avatar: this.store.apartmentData.avatar,
        signContractDate: data.signContractDate,
        endContractDate: data.endContractDate,
        rent: parseInt(data.rent),
        country: data.country,
        leaseMonth: parseInt(data.leaseMonth),
        deposit: parseInt(data.deposit),
        callingCode: data.callingCode,
        rentNotification: data.rentNotification,
        endContractNotification: data.endContractNotification,
        rentNotificationId: data.rentNotificationId,
        remark: this.store.apartmentDataRemark,
        doc: this.store.apartmentDataDoc,
      };

      console.log(newApartment);

      if (this.store.logined) {
        await this.store.createApartmentPost(newApartment, true);
        await realm.write(() => {
          user[0].apartment.push(newApartment);
          newApartment.rentNotificationId.map(async (items, index) => {
            await user[0].notification.push(items);
          });
        });
        await this.store.loadLocalData();
        this.props.navigation.popToTop();
        //  await this.store.uploadDocFetch(newApartment.id,this.store.apartmentDataDoc),
      } else {
        try {
          await realm.write(() => {
            user[0].apartment.push(newApartment);
            newApartment.rentNotificationId.map(async (items, index) => {
              await user[0].notification.push(items);
            });
          });
        } catch (error) {
          console.log(error);
        }

        await this.store.loadLocalData();
        this.props.navigation.popToTop();
      }
      // history.pop(this,1)
    } catch (e) {
      console.log('Error on creation ' + e);
    }
  }

  referYourFriender() {
    //const link = Platform.OS === 'ios' ? 'itms://itunes.apple.com/us/app/apple-store/1439173696?mt=8'  : '';
    var sharemessage = '';
    if (this.store.language == 'english') {
      sharemessage = 'share ';
    } else {
      sharemessage = 'share ';
    }
    const link = 'http://onelink.to/mh4dh2';
    Share.share({
      message: sharemessage + link,
      title: 'Hangry no more',
    });
  }

  addTenant() {
    Alert.alert(
      '',
      'Please login',
      [
        {
          text: 'OK',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
      ],
      {cancelable: false},
    );
  }

  render() {
    console.log(this.store.image);
    var data = this.store.apartmentData;
    return (
      <View
        style={{
          flex: 1,
        }}>
        <LoadingView visible={this.store.loading} />

        <BackHeader instance={this} back={true} />

        <View style={{flex: 1, alignItems: 'center'}}>
          {/* <View style={{ flexDirection: 'row' }}>
                    <Text style={styles.textView}>
                        {this.store.text.addTenant}
                    </Text>
                    <Switch
                        value={this.AddTenantSwitch}
                        backgroundActive={colors.mainColor}
                        onSyncPress={(value) => { this.AddTenantSwitch = value }} />
                </View>
                <View style={{ flexDirection: 'row' }}>
                    <Text style={styles.textView}>
                        {this.store.text.share}
                    </Text>
                    <Icon name='share-alt' solid size={30} onPress={() => { this.referYourFriender(); }} />
                </View> */}
          <View style={styles.slide1}>
            <View style={styles.shadowView}>
              <Image
                style={{
                  marginTop: 2,
                  width: scale(275),
                  height: verticalScale(200),
                  backgroundColor: '#F0F3F4',
                }}
                resizeMode={'contain'}
                source={{uri: this.store.apartmentData.avatar}}
              />
              {this.list(
                this.store.text.apartment,
                data.name,
                colors.textColor,
              )}
              {this.list(
                this.store.text.address,
                data.address,
                colors.textColor,
              )}
              {this.list(
                this.store.text.rent,
                'HKD ' + data.rent,
                colors.textColor,
              )}
              {this.list(
                this.store.text.rentDay,
                this.dateStringHandler(data.signContractDate),
                colors.textColor,
              )}
              {this.list(
                this.store.text.contractExpiry,
                this.dateStringHandler(data.endContractDate),
                colors.textColor,
              )}
              {this.list(
                this.store.text.country,
                this.store.getCountryLabel(data.country),
                colors.textColor,
              )}
              {this.list(
                this.store.text.notificationOfCollectRents,
                data.rentNotification,
                colors.textColor,
              )}
              {this.list(
                this.store.text.notificationOfcontractExpiry,
                data.endContractNotification,
                colors.textColor,
              )}
              {/* <TouchableOpacity style={{ flexDirection: 'row', marginRight: 5, marginLeft: 5, marginTop: 10, width: scale(265) }}
                                onPress={() => { this.addTenant() }} >
                                <Text style={{ fontFamily: Fonts.ubuntu, fontSize: 17, color: colors.mainColor }}>
                                    Add Tenant now?
                </Text>
                            </TouchableOpacity> */}
            </View>
          </View>
        </View>

        <View style={{width: width, alignItems: 'center'}}>
          <TouchableOpacity
            onPress={() => {
              this.saveAction();
            }}
            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}}>
              {this.store.text.ok}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  button: {
    marginTop: 20,
    width: 100,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  buttonText: {
    color: '#fff',
  },
  textView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntu,
    fontSize: 17,
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },

  shadowView: {
    width: scale(280),
    height: verticalScale(460),
    alignItems: 'center',
    borderWidth: 0.5,
    backgroundColor: 'white',
    borderColor: '#EAEDED',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,

    elevation: 2,
  },

  text: {
    marginTop: 7,
    color: colors.textColor,
    fontSize: 19,
    fontFamily: Fonts.ubuntu,
  },
});
