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 StepIndicator from 'react-native-step-indicator'
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 moment from "moment"
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";
const asyncStorageHelper = new AsyncStorageHelper;

let realm = new Realm({ schema: [UserSchemea, ApartmentSchemea, DocSchemea,NotificationSchemea] });
const secondIndicatorStyles = {
    stepIndicatorSize: 30,
    currentStepIndicatorSize: 40,
    separatorStrokeWidth: 2,
    currentStepStrokeWidth: 3,
    stepStrokeCurrentColor: colors.mainColor,
    stepStrokeWidth: 3,
    separatorStrokeFinishedWidth: 4,
    stepStrokeFinishedColor: colors.mainColor,
    stepStrokeUnFinishedColor: '#aaaaaa',
    separatorFinishedColor: colors.mainColor,
    separatorUnFinishedColor: '#aaaaaa',
    stepIndicatorFinishedColor: colors.mainColor,
    stepIndicatorUnFinishedColor: '#ffffff',
    stepIndicatorCurrentColor: '#ffffff',
    stepIndicatorLabelFontSize: 13,
    currentStepIndicatorLabelFontSize: 13,
    stepIndicatorLabelCurrentColor: colors.mainColor,
    stepIndicatorLabelFinishedColor: '#ffffff',
    stepIndicatorLabelUnFinishedColor: '#aaaaaa',
    labelColor: '#999999',
    labelSize: 13,
    currentStepLabelColor: colors.mainColor
}

const getStepIndicatorIconConfig = ({ position, stepStatus }) => {
    const iconConfig = {
        name: 'feed',
        color: stepStatus === 'finished' ? '#ffffff' : colors.mainColor,
        size: 15
    }
    switch (position) {
        case 0: {
            iconConfig.name = 'cart-arrow-down'
            break
        }
        case 1: {
            iconConfig.name = 'wrench'
            break
        }
        case 2: {
            iconConfig.name = 'check'
            break
        }

        default: {
            break
        }
    }
    return iconConfig
}

@inject("appStore")
@observer
export default class HistoryDetails extends Component {

    @observable
    data = null

    @observable
    status = 0

    @observable
    paymentVisable = false

    @observable
    serviceInfoVisable = true

    @observable
    ownerInfoVisable = false

    @observable
    tenantInfoVisable = false

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

    dateHandler(date){
        return moment(date).format('L');
     }

    dateHandlerTime(date){
        return moment(date).format('L, hh:mm');
    }

    componentDidMount() {
        this.getStatus()
    }

    getStatus() {
        switch (this.data.status) {
            case 'Pending Payment':
                this.status = 0
                break;
            case 'Processing':
                this.status = 1
                break;
            case 'Completed':
                this.status = 2
                break;
        }
    }

    logList(item) {
        console.log(item)
        return (
            <View style={{ marginRight: 5, marginLeft: 5, backgroundColor: 'F0F3F4', marginBottom: 10 }} >
                <Text style={styles.text}>
                    {this.dateHandlerTime(item.createDate)}
                </Text>
                <Text style={styles.text}>
                    {item.remark}
                </Text>
            </View>
        )
    }

    renderStepIndicator = params => (
        <Icon {...getStepIndicatorIconConfig(params)} />
    )

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

    renderServiceInfo() {
        if (this.serviceInfoVisable) {
            return (
                <View style={{ width: width, backgroundColor: '#E7E7E7' }}>
                    <Text style={styles.text}>
                        {'ID: ' + this.data.id}
                    </Text>
                    <Text style={styles.text}>
                        {'Date: ' + this.dateHandler(this.data.date)}
                    </Text>
                    <Text style={styles.text}>
                        {'Apartment Name: ' + this.data.apartment.name}
                    </Text>
                    <Text style={styles.text}>
                        {'Address: ' + this.data.apartment.address}
                    </Text>
                    <Text style={[styles.text]}>
                        {'Problems: ' + this.data.description}
                    </Text>

                    <Text style={[styles.text, { marginBottom: 10 }]}>
                        {'Service cost: ' + 'HKD ' + this.data.cost}
                    </Text>
                </View>
            )
        } else {
            return null
        }

    }

    renderOwnerInfo() {
        if (this.ownerInfoVisable) {
            return (
                <View style={{ width: width, backgroundColor: '#E7E7E7' }}>
                    <Text style={styles.text}>
                        {'Owner: ' + this.data.apartment.owner.fullname}
                    </Text>
                    <Text style={[styles.text, { marginBottom: 10 }]}>
                        {'Owner Phone Number: ' + "+" + this.data.apartment.owner.countryCode + " " + this.data.apartment.owner.phone}
                    </Text>
                </View>
            )
        } else {
            return null
        }

    }

    renderTenantInfo() {
        if (this.tenantInfoVisable) {
            return (
                <View style={{ width: width, backgroundColor: '#E7E7E7' }}>
                    <Text style={styles.text}>
                        {'Tenant: ' + this.data.apartment.tenant.fullname}
                    </Text>
                    <Text style={[styles.text, { marginBottom: 10 }]}>
                        {'Tenant Phone Number: ' + "+" + this.data.apartment.tenant.countryCode + " " + this.data.apartment.tenant.phone}
                    </Text>

                </View>
            )
        } else {
            return null
        }

    }



    upDownContorl(index) {
        switch (index) {
            case 0:
                if (this.serviceInfoVisable) {
                    return 'caret-up'
                } else {
                    return 'caret-down'
                }
                break;

            case 1:
                if (this.ownerInfoVisable) {
                    return 'caret-up'
                } else {
                    return 'caret-down'
                }
                break;

            case 2:
                if (this.tenantInfoVisable) {
                    return 'caret-up'
                } else {
                    return 'caret-down'
                }
                break;
        }
    }

    renderPayBar(){
        if (this.data.cost == 0){
           return(
             null
           )
        }else{
           return(
<TouchableOpacity 
onPress = {()=>{this.paymentVisable = true}}
style = {{flexDirection:'row', width:width, height:50,backgroundColor:colors.mainColor,justifyContent:'space-between',alignItems:'center'}}>
                     <Text style = {{marginLeft:20, fontFamily:Fonts.ubuntu,color:'white',fontSize:17}}>
                         {'HKD '+this.data.cost}
                     </Text>
                     <Text style = {{marginRight:20, fontFamily:Fonts.ubuntu,color:'white',fontSize:17}}>
                         {'Pay'}
                     </Text>
                </TouchableOpacity>
           )
        }
    }

    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
    }


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

                <BackHeader instance={this} back={true} />
                <LoadingView visible={this.store.loading} />
                <ScrollView >
                    <View style={{ flex: 1, alignSelf: 'center' }}>


                        <View style={styles.stepIndicator}>
                            <StepIndicator
                                stepCount={3}
                                renderStepIndicator={this.renderStepIndicator}
                                customStyles={secondIndicatorStyles}
                                currentPosition={this.status}
                                labels={[
                                    'Payment',
                                    'Processing',
                                    'Completed',
                                ]}
                            />
                        </View>
                        <View style={{ width: width, alignItems: 'center' }}>
                            <Text style={styles.titieStyle}>
                                Information
           </Text>
                        </View>

                        <TouchableOpacity style={{ flexDirection: 'row', marginTop: 10 }} onPress={() => { this.serviceInfoVisable = !this.serviceInfoVisable }}>
                            <Text style={styles.subTitle}>
                                Service Info
               </Text>

                            <Icon style={{ marginLeft: 20, marginTop: scale(2) }} name={this.upDownContorl(0)} size={20} soild color={colors.mainColor} />

                        </TouchableOpacity>
                        {this.renderServiceInfo()}

                        <TouchableOpacity style={{ flexDirection: 'row', marginTop: 10 }} onPress={() => { this.ownerInfoVisable = !this.ownerInfoVisable }}>
                            <Text style={styles.subTitle}>
                                Owner Info
               </Text>

                            <Icon style={{ marginLeft: 20, marginTop: scale(2) }} name={this.upDownContorl(1)} size={20} soild color={colors.mainColor} />

                        </TouchableOpacity>
                        {this.renderOwnerInfo()}
                        <TouchableOpacity style={{ flexDirection: 'row', marginTop: 10 }} onPress={() => { this.tenantInfoVisable = !this.tenantInfoVisable }}>
                            <Text style={styles.subTitle}>
                                Tenant Info
               </Text>

                            <Icon style={{ marginLeft: 20, marginTop: scale(2) }} name={this.upDownContorl(2)} size={20} soild color={colors.mainColor} />

                        </TouchableOpacity>
                        {this.renderTenantInfo()}

                        <View style={{ width: width, alignItems: 'center' }}>
                            <Text style={[styles.titieStyle, { marginTop: 15 }]}>
                                Log
           </Text>
                        </View>
                        <View style={{ width: width, alignItems: 'center', marginTop: 15, marginBottom: 20 }}>
                            <View style={{
                                width: width - 20, height: 250, borderColor: colors.textColor, borderWidth: 1, backgroundColor: 'white', shadowColor: "#000",
                                shadowOffset: {
                                    width: 0,
                                    height: 1,
                                },
                                shadowOpacity: 0.20,
                                shadowRadius: 1.41,

                                elevation: 2,
                            }}>
                                <ScrollView>
                                    {this.data.log.map((items, index) => {
                                        return this.logList(items)
                                    })}
                                </ScrollView>
                            </View>
                        </View>

                    </View>
                </ScrollView>

                {this.renderPayBar()}
     <Modal
          visible={this.paymentVisable}
          width={0.7}
          height={0.2}
          onTouchOutside={() => {
            this.paymentVisable = false;
          }}
          swipeDirection={["up", "down"]} // can be string or an array
          swipeThreshold={200} // default 100
          onSwipeOut={event => {
            this.paymentVisable = false;
          }}
        >
          <ModalContent>
            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
                justifyContent: "center"
              }}
            >
              <TouchableOpacity
                style={{ alignItems: "center" }}
                onPress={() => {
                  this.store.alipayment(this.data.id,this.data.cost,this)
                  this.paymentVisable = false;
                }}
              >
                <Icon
                  name="alipay"
                  sholid
                  color={colors.mainColor}
                  size={40}
                />
                <Text
                  style={{ fontFamily: Fonts.ubuntu, color: colors.mainColor }}
                >
               {'Alipay'}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{ alignItems: "center", marginLeft: 30 }}
                onPress={() => {
                  history.push(this, "/uploadImage", {
                    index: this.index,
                    create: false
                  });
                  this.docVisable = false;
                }}
              >
                <Icon
                  name="credit-card"
                  sholid
                  color={colors.mainColor}
                  size={40}
                />
                <Text
                  style={{ fontFamily: Fonts.ubuntu, color: colors.mainColor }}
                >
                  {'Credit Card'}
                </Text>
              </TouchableOpacity>
            </View>
          </ModalContent>
        </Modal>

            </View >
        );
    }
}

const styles = StyleSheet.flatten({

    titleView: {
        marginRight: 5, marginLeft: 5, marginTop: 10, width: scale(265)
    },

    titieStyle: {
        fontSize: 20,
        color: colors.mainColor,
        fontFamily: Fonts.ubuntu,

    },
    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(500),
        alignItems: 'center',
        borderWidth: 0.5,
        backgroundColor: 'white',
        borderColor: '#EAEDED',
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 1,
        },
        shadowOpacity: 0.20,
        shadowRadius: 1.41,

        elevation: 2,
    },

    subTitle: {
        marginTop: 5,
        marginLeft: 10,
        marginRight: 10,
        color: colors.mainColor,
        fontSize: 15,
        fontFamily: Fonts.ubuntu,
    },

    text: {
        marginTop: 5,
        marginLeft: 10,
        marginRight: 10,
        color: colors.textColor,
        fontSize: 14,
        fontFamily: Fonts.ubuntu,
    },
    stepIndicator: {
        marginVertical: 50
    },
});
