import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Image,
  //Share,
  Alert,
  Platform,
} from 'react-native';
import ViewShot from 'react-native-view-shot';
import Share from 'react-native-share';
import RNImageToPdf from 'react-native-image-to-pdf';
import moment from 'moment';
import CameraRoll from '@react-native-community/cameraroll';
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Toast, {DURATION} from 'react-native-easy-toast';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Modal, {ModalContent} from 'react-native-modals';
import Switch from 'react-native-switch-pro';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import Realm from 'realm';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import LoadingView from '../../common/loading';
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';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';

let unique = 0;
const {SlideInMenu} = renderers;
const asyncStorageHelper = new AsyncStorageHelper();

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

@inject('appStore')
@observer
export default class ReceiptDetails extends Component {
  @observable
  data = null;

  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.data = this.props.navigation.state.params.receiptData;
  }

  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={{width: scale(200)}}>
          <Text style={{fontFamily: Fonts.ubuntu, color: color}}>
            {contents}
          </Text>
        </View>
      </View>
    );
  }

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

  saveAsFunction(value) {
    this.refs.viewShot.capture().then(uri => {
      console.log('do something with ', uri);
      if (value === 2) {
        this.myAsyncPDFFunction(uri);
      } else if (value === 1) {
        this.saveImage(uri);
      } else {
        this.shareIt(uri);
      }
    });
  }

  async shareIt(uri) {
    const shareOptions = {
      title: this.data.date + ' 的租金收據',
      url: uri,
    };

    try {
      const ShareResponse = await Share.open(shareOptions);
      setResult(JSON.stringify(ShareResponse, null, 2));
    } catch (error) {
      console.log('Error =>', error);
      setResult('error: '.concat(getErrorString(error)));
    }
  }

  async saveImage(uri) {
    if (Platform.OS === 'android') {
      // RNFetchBlob.config({
      //   fileCache: true,
      //   appendExt: 'jpg',
      // })
      //   .fetch('GET', image.urls.small)
      //   .then(res => {
      //     CameraRoll.saveToCameraRoll(res.path())
      //       .then(Alert.alert('Success', 'Photo added to camera roll!'))
      //       .catch(err => console.log('err:', err));
      //   });
    } else {
      await CameraRoll.saveToCameraRoll(uri).then(
        this.refs.toast.show('Saved, Photo added to camera roll.'),
      );
    }
  }

  async myAsyncPDFFunction(uri) {
    var data = [uri];
    try {
      const options = {
        imagePaths: data,
        name: 'receipt' + moment().format('YYYYMMDDhhmmss'),
      };
      const pdf = await RNImageToPdf.createPDFbyImages(options);
      this.refs.toast.show('Saved');
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    console.log(this.store.image);
    var data = this.store.apartmentData;
    return (
      <MenuProvider style={{flex: 1}}>
        <View
          style={{
            flex: 1,
          }}>
          <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.receipt}
            </Text>
            <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>

            <View
              style={{
                position: 'absolute',
                right: 20,
                justifyContent: 'center',
                alignItems: 'center',
                height: 40,
                width: 40,
              }}>
              <Menu
                name="share"
                renderer={SlideInMenu}
                onSelect={value => this.saveAsFunction(value)}>
                <MenuTrigger>
                  <MaterialCommunityIcons
                    name={'export-variant'}
                    size={30}
                    color={'white'}
                    style={{
                      ...Platform.select({
                        ios: {},
                        android: {
                          //top: 40,
                        },
                      }),
                    }}
                  />
                </MenuTrigger>
                <MenuOptions
                  customStyles={{
                    optionText: {
                      margin: 5,
                      fontFamily: Fonts.ubuntu,
                      color: 'white',
                    },
                    optionWrapper: {
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                    },
                  }}
                  >
                  <MenuOption value={1}>
                    <Text
                      style={{
                        color:'white',
                        fontFamily: Fonts.ubuntu,
                        fontSize:18
                      }}>
                      {this.store.text.saveAsImage}
                    </Text>
                  </MenuOption>
                  <MenuOption value={2}>
                    <Text
                      style={{
                        color:'white',
                        fontFamily: Fonts.ubuntu,
                        fontSize:18
                      }}>
                      {this.store.text.saveAsPdf}
                    </Text>
                  </MenuOption>
                  <MenuOption value={3}>
                    <Text
                      style={{
                        color:'white',
                        fontFamily: Fonts.ubuntu,
                        fontSize:18
                      }}>
                      {'分享'}
                    </Text>
                  </MenuOption>
                </MenuOptions>
              </Menu>
            </View>
          </View>
          <LoadingView visible={this.store.loading} />
          <View
            style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
            <ScrollView style={{flex: 1}}>
              <ViewShot
                ref="viewShot"
                options={{format: 'jpg', quality: 0.9}}
                captureMode="mount">
                <View
                  style={{
                    alignItems: 'center',
                    marginTop: 20,
                    marginBottom: 20,
                    shadowColor: '#000',
                    backgroundColor: 'white',
                    width: width - 40,
                    borderRadius: 5,
                    shadowColor: '#000',
                    shadowOffset: {
                      width: 0,
                      height: 4,
                    },
                    shadowOpacity: 0.32,
                    shadowRadius: 5.46,

                    elevation: 9,
                  }}>
                  <View style={{width: width - 40}}>
                    <Text style={[styles.title, {marginTop: 20}]}>
                      正式收據 OFFICAL RECEIPT
                    </Text>
                  </View>

                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <SubTitle
                    titleCh="收據編號"
                    titleEn="ReceiptNo."
                    fontColor="black"
                    content={'' + this.data.id}
                  />
                  <SubTitle
                    titleCh="單位"
                    titleEn="Unit"
                    fontColor="black"
                    content={this.store.apartmentsData[this.data.index].name}
                  />
                  <SubTitle
                    titleCh="地址"
                    titleEn="Address"
                    fontColor="black"
                    content={this.data.address}
                  />
                  <SubTitle
                    titleCh="租期"
                    titleEn="Lease"
                    fontColor="black"
                    content={this.data.date}
                  />
                  <SubTitle
                    titleCh="應繳租金"
                    titleEn="Rent"
                    fontColor="black"
                    content={this.data.rent}
                  />
                  <SubTitle
                    titleCh="現收租金"
                    titleEn="Rent"
                    fontColor="black"
                    content={this.data.rent}
                  />
                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <View style={{width: width - 40}}>
                    <Text style={[styles.title, {marginTop: 10}]}>
                      出租人 LESSOR
                    </Text>
                  </View>

                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <SubTitle
                    titleCh="出租人"
                    titleEn="Lessor"
                    fontColor="black"
                    content={this.data.owner}
                  />
                  <SubTitle
                    titleCh="電話"
                    titleEn="Phone"
                    fontColor={colors.mainColor}
                    content={this.data.ownerPhone}
                  />

                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <View style={{width: width - 40}}>
                    <Text style={[styles.title, {marginTop: 10}]}>
                      承租人 LESSEE
                    </Text>
                  </View>

                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <SubTitle
                    titleCh="承租人"
                    titleEn="LESSEE"
                    fontColor="black"
                    content={this.data.tenant}
                  />
                  <SubTitle
                    titleCh="電話"
                    titleEn="Phone"
                    fontColor={colors.mainColor}
                    content={this.data.tenantPhone}
                  />
                  <SubTitle
                    titleCh="地址"
                    titleEn="Address"
                    fontColor={'black'}
                    content={this.data.address}
                  />
                  <View
                    style={{
                      height: 1,
                      backgroundColor: colors.textColor,
                      width: width - 80,
                      marginTop: 10,
                    }}
                  />
                  <View
                    style={{
                      flexDirection: 'row',
                      marginLeft: 20,
                      marginRight: 20,
                      marginTop: 10,
                    }}>
                    <View style={{flex: 0.6}}>
                      <View>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {'業主簽署'}
                        </Text>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {`Proprietor's Signature`}
                        </Text>
                      </View>
                    </View>

                    <View style={{flex: 0.4}}>
                      <Image
                        source={{
                          uri: this.store.apartmentsData[this.data.index].owner
                            .sign,
                        }}
                        resizeMode={'contain'}
                        style={{width: 50, height: 50}}
                      />
                    </View>
                  </View>
                  <View
                    style={{
                      flexDirection: 'row',
                      marginLeft: 20,
                      marginRight: 20,
                      marginTop: 10,
                    }}>
                    <View style={{flex: 0.6}}>
                      <View>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {'業主姓名'}
                        </Text>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {`Proprietor's Name`}
                        </Text>
                      </View>
                    </View>

                    <View style={{flex: 0.4}}>
                      <Text style={{color: 'black', fontFamily: Fonts.ubuntuL}}>
                        {this.data.owner}
                      </Text>
                    </View>
                  </View>
                  <View
                    style={{
                      flexDirection: 'row',
                      marginLeft: 20,
                      marginRight: 20,
                      marginBottom: 40,
                      marginTop: 30,
                    }}>
                    <View style={{flex: 0.6}}>
                      <View>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {'日期'}
                        </Text>
                        <Text
                          style={{
                            color: colors.line2Color,
                            fontFamily: Fonts.ubuntu,
                          }}>
                          {`Date`}
                        </Text>
                      </View>
                    </View>

                    <View style={{flex: 0.4}}>
                      <Text style={{color: 'black', fontFamily: Fonts.ubuntuL}}>
                        {this.data.signDate}
                      </Text>
                    </View>
                  </View>
                </View>
              </ViewShot>
            </ScrollView>
          </View>
          <Toast
            ref="toast"
            style={{backgroundColor: colors.mainColor}}
            position="bottom"
            positionValue={200}
            fadeInDuration={750}
            fadeOutDuration={2000}
            opacity={0.8}
            textStyle={{color: 'white'}}
          />
        </View>
      </MenuProvider>
    );
  }
}

const SubTitle = props => {
  return (
    <View
      style={{
        flexDirection: 'row',
        marginLeft: 20,
        marginRight: 20,
        marginTop: 10,
      }}>
      <View style={{flex: 0.3}}>
        <View>
          <Text style={{color: colors.line2Color, fontFamily: Fonts.ubuntu}}>
            {props.titleCh}
          </Text>
          <Text style={{color: colors.line2Color, fontFamily: Fonts.ubuntu}}>
            {props.titleEn}
          </Text>
        </View>
      </View>

      <View style={{flex: 0.7}}>
        <Text style={{color: props.fontColor, fontFamily: Fonts.ubuntuL}}>
          {props.content}
        </Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.flatten({
  titleView: {
    marginRight: 5,
    marginLeft: 5,
    marginTop: 10,
    width: scale(265),
  },

  titieStyle: {
    fontSize: 20,
    color: colors.mainColor,
    fontFamily: Fonts.ubuntu,
    marginRight: 5,
    marginLeft: 5,
    marginTop: 20,
  },
  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(370),
    alignItems: 'center',
    borderWidth: 0.5,
    backgroundColor: 'white',
    borderColor: '#EAEDED',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,

    elevation: 2,
  },
  title: {
    fontSize: 17,
    marginLeft: 20,
    color: 'black',
    fontFamily: Fonts.ubuntu,
  },

  text: {
    marginTop: 7,
    color: colors.textColor,
    fontSize: 19,
    fontFamily: Fonts.ubuntu,
  },
  triggerText: {
    color: 'white',
  },
  slideInOption: {
    padding: 5,
  },
});
