import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Image,
  Share,
  Alert,
  Platform,
  TextInput,
  TouchableHighlightBase,
} from 'react-native';
import ViewShot from 'react-native-view-shot';
import CheckAnimate from '../../common/checkAnimate';
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 {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
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 ProblemCase extends Component {
  @observable
  data = null;
  @observable
  statusDisable = false;
  @observable
  editable = false;
  @observable
  buttonVisable = true;
  @observable
  caseData = {
    id: '',
    createDate: '',
    status: 'Processing',
    content: '',
    log: [{content: ''}],
  };

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

  async caseDataInit() {
    this.caseData.id = this.data.id;
    if (this.props.navigation.state.params.type == 'create') {
      this.statusDisable = true;
      this.caseData.createDate = moment().format('DD/MM/YYYY');
      this.editable = true;
    } else {
      this.caseData.status = this.props.navigation.state.params.data.status;
      this.caseData.createDate = moment(
        this.props.navigation.state.params.data.createDate,
      ).format('DD/MM/YYYY');
      this.caseData.content = this.props.navigation.state.params.data.description;
      this.editable = false;
      this.caseData.log = [];
      await this.props.navigation.state.params.data.log.map((items, index) => {
        this.caseData.log.push(items);
      });
      if (this.props.navigation.state.params.data.status == 'Completed') {
        this.buttonVisable = false;
        this.statusDisable = true;
      } else {
        var user = 0;
        if (this.store.loginUserData.data.member.chara == 'owner') {
          user = 0;
        } else {
          user = 1;
        }
        if (this.props.navigation.state.params.data.mtype != user) {
          //   this.buttonVisable = false;

          this.statusDisable = true;
        } else {
          //   this.buttonVisable = true;
          if (
            this.props.navigation.state.params.data.hasOwnProperty('helper')
          ) {
            this.statusDisable = true;
          }
        }
      }
    }
  }

  componentDidMount() {
    this.caseDataInit();
  }

  casePay() {
    //if(this.store.loginUserData.data.member)
    if (this.store.addedCard) {
      var id = this.props.navigation.state.params.data.id;
      this.store.casePayByCredit(id, this);
    } else {
      this.refs.toast.show('請先加入信用卡');
    }
  }

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

  renderCompleteButton() {
    if (this.props.navigation.state.params.type == 'create') {
      return (
        <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>
      );
    } else {
      if (this.props.navigation.state.params.data.status != 'Completed') {
        if (this.props.navigation.state.params.data.cost > 0) {
          if (
            this.props.navigation.state.params.data.client.id ==
              this.store.loginUserData.data.member.id &&
            this.props.navigation.state.params.data.status == 'Pending Payment'
          ) {
            return (
              <TouchableOpacity
                onPress={() => {
                  this.casePay();
                }}
                style={{
                  position: 'absolute',
                  right: 20,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    fontSize: 17,
                    color: 'white',
                  }}>
                  {this.store.text.pay}
                </Text>
              </TouchableOpacity>
            );
          } else {
            return (
              <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>
            );
          }
        }
        return (
          <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>
        );
      } else {
        return <View></View>;
      }
    }
  }

  renderPaybutton() {}

  statusSelection(data) {
    console.log(data);
    this.caseData.status = data;
  }

  remarkEditable(index) {
    if (this.props.navigation.state.params.data != null) {
      if (index >= this.props.navigation.state.params.data.log.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }

  renderPaymentInfo() {
    if (this.props.navigation.state.params.data != null) {
      if (
        this.props.navigation.state.params.data.client.id ==
          this.store.loginUserData.data.member.id &&
        this.props.navigation.state.params.data.cost > 0
      ) {
        return (
          <View>
            <View
              style={{
                width: width,
                marginLeft: 20,
                backgroundColor: colors.line2Color,
                height: 1,
              }}
            />
            <View style={{margin: 20}}>
              <View>
                <Text style={[styles.title, {fontSize: 17}]}>{'需付金額'}</Text>
                <View style={{flex: 1, flexDirection: 'row', marginTop: 10}}>
                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {'金額'}
                    </Text>
                    <Text style={styles.textView}>
                      {'HKD ' + this.props.navigation.state.params.data.cost}
                    </Text>
                  </View>

                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {'付款狀態'}
                    </Text>
                    <Text style={[styles.textView, {color: colors.mainColor}]}>
                      {this.props.navigation.state.params.data.status ==
                      'Pending Payment'
                        ? '未付款'
                        : '已付款'}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
        );
      }
    }
  }

  renderRemark() {
    return this.caseData.log.map((items, index) => {
      if (!items.hasOwnProperty('name')) {
        return (
          <View
            style={{
              marginTop: 20,
              borderBottomWidth: 1,
              borderBottomColor: colors.line2Color,
            }}>
            <View
              style={{flexDirection: 'row', marginBottom: 5, marginTop: 20}}>
              <View style={{flex: 0.8}}>
                <TextInput
                  placeholder={'記錄(Log)'}
                  editable={this.remarkEditable(index)}
                  placeholderStyle={{fontFamily: Fonts.ubuntuL}}
                  placeholderTextColor={colors.line2Color}
                  underlineColorAndroid="rgba(0,0,0,0)"
                  style={{
                    fontSize: 20,
                    color: 'black',
                    fontFamily: Fonts.ubuntuTh,
                  }}
                  value={this.caseData.log[index].content}
                  onChangeText={text => {
                    this.caseData.log[index].content = text;
                  }}
                />
              </View>
              <TouchableOpacity
                disabled={!this.remarkEditable(index)}
                style={{flex: 0.2, alignItems: 'flex-end', marginRight: 10}}
                onPress={() => {
                  this.caseData.log.splice(index, 1);
                  this.buttonVisable = true;
                }}>
                <Icon name="times-circle" color={'black'} size={20} solid />
              </TouchableOpacity>
            </View>
          </View>
        );
      } else {
        return (
          <View
            style={{
              marginTop: 20,
            }}>
            <View
              style={{
                marginBottom: 5,
                marginTop: 20,
                borderBottomWidth: 1,
                borderBottomColor: colors.line2Color,
              }}>
              <View style={{flex: 1}}>
                <TextInput
                  placeholder={'記錄(Log)'}
                  editable={this.remarkEditable(index)}
                  placeholderStyle={{fontFamily: Fonts.ubuntuL}}
                  placeholderTextColor={colors.line2Color}
                  underlineColorAndroid="rgba(0,0,0,0)"
                  style={{
                    fontSize: 20,
                    color: 'black',
                    fontFamily: Fonts.ubuntuTh,
                  }}
                  value={this.caseData.log[index].content}
                  onChangeText={text => {
                    this.caseData.log[index].content = text;
                  }}
                />
              </View>
            </View>
            <View style={{flex: 1, flexDirection: 'row'}}>
              <View style={{flex: 0.5}}>
                <Text style={styles.nameAndDate}>{items.name}</Text>
              </View>
              <View style={{flex: 0.5, alignItems: 'flex-end'}}>
                <Text style={styles.nameAndDate}>
                  {moment(items.createDate).format('DD/MM/YYYY hh:mm')}
                </Text>
              </View>
            </View>
          </View>
        );
      }
    });
  }

  statusTextReturn() {
    switch (this.caseData.status) {
      case 'Processing':
        return this.store.text.process;
        break;
      case 'Pending Payment':
        return this.store.text.pendingPayment;
      case 'Completed':
        return this.store.text.closeFile;
        break;
    }
  }

  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>
    );
  }

  async completeClickAcion() {
    if (this.caseData.content != '' || this.caseData.content.length > 0) {
      if (this.props.navigation.state.params.type == 'create') {
        this.store.postCase(this.caseData, this);
      } else {
        if (this.caseData.status == 'Completed') {
          if (
            this.caseData.log.length >
            this.props.navigation.state.params.data.log.length
          ) {
            await this.store.updateCaseLog(
              this.caseData.log[
                this.props.navigation.state.params.data.log.length
              ],
              this.props.navigation.state.params.data.id,
              false,
              this,
            );

            this.store.finishCase(
              true,
              this,
              this.props.navigation.state.params.data.id,
            );
          } else {
            this.store.finishCase(
              true,
              this,
              this.props.navigation.state.params.data.id,
            );
          }
        } else {
          if (
            this.caseData.log.length >
            this.props.navigation.state.params.data.log.length
          ) {
            await this.store.updateCaseLog(
              this.caseData.log[
                this.props.navigation.state.params.data.log.length
              ],
              this.props.navigation.state.params.data.id,
              true,
              this,
            );
          } else {
            this.props.navigation.popToTop();
          }
        }
      }
    } else {
      this.refs.toast.show('Please input problems');
    }
  }

  render() {
    return (
      <MenuProvider style={{flex: 1}}>
        <View
          style={{
            flex: 1,
            backgroundColor:'white'
          }}>
          <CheckAnimate
            visible={this.store.animateStatus.show}
            progress={this.store.animateStatus.progress}
          />
          <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.report + this.store.text.problems}
            </Text>
            {this.renderBackIcon()}
            {this.renderCompleteButton()}
          </View>

          <LoadingView visible={this.store.loading} />

          <KeyboardAwareScrollView style={{flex: 1}}>
            <View style={{margin: 20}}>
              <Text style={styles.title}>{this.store.text.propertyinfo}</Text>
              <Text style={[styles.textView, {marginTop: 10}]}>
                {this.data.name}
              </Text>
              <Text style={[styles.textView]}>{this.data.address}</Text>
              <View style={{flex: 1, flexDirection: 'row', marginTop: 10}}>
                <View style={{flex: 0.5}}>
                  <Text style={[styles.textView, {color: colors.line2Color}]}>
                    {this.store.text.id}
                  </Text>
                  <Text numberOfLines={1} style={styles.textView}>
                    {this.data.id}
                  </Text>
                </View>

                <View style={{flex: 0.5}}>
                  <Text style={[styles.textView, {color: colors.line2Color}]}>
                    {this.store.text.date}
                  </Text>
                  <Text style={styles.textView}>
                    {this.caseData.createDate}
                  </Text>
                </View>
              </View>
            </View>
            <View
              style={{
                width: width,
                marginLeft: 20,
                backgroundColor: colors.line2Color,
                height: 1,
              }}
            />
            <View style={{margin: 20}}>
              <View>
                <Text style={[styles.title, {fontSize: 17}]}>
                  {this.store.text.owner + this.store.text.info}
                </Text>
                <View style={{flex: 1, flexDirection: 'row', marginTop: 10}}>
                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {this.store.text.owner}
                    </Text>
                    <Text style={styles.textView}>
                      {this.data.owner.fullname}
                    </Text>
                  </View>

                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {this.store.text.phonenumber}
                    </Text>
                    <Text style={[styles.textView, {color: colors.mainColor}]}>
                      {'+' +
                        this.data.owner.countryCode +
                        ' ' +
                        this.data.owner.phone}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
            <View
              style={{
                width: width,
                marginLeft: 20,
                backgroundColor: colors.line2Color,
                height: 1,
              }}
            />
            <View style={{margin: 20}}>
              <View>
                <Text style={[styles.title, {fontSize: 17}]}>
                  {this.store.text.tenant + this.store.text.info}
                </Text>
                <View style={{flex: 1, flexDirection: 'row', marginTop: 10}}>
                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {this.store.text.tenant}
                    </Text>
                    <Text style={styles.textView}>
                      {this.data.hasOwnProperty('tenant')
                        ? this.data.tenant.fullname
                        : '--'}
                    </Text>
                  </View>

                  <View style={{flex: 0.5}}>
                    <Text style={[styles.textView, {color: colors.line2Color}]}>
                      {this.store.text.phonenumber}
                    </Text>
                    <Text style={[styles.textView, {color: colors.mainColor}]}>
                      {this.data.hasOwnProperty('tenant')
                        ? '+' +
                          this.data.tenant.countryCode +
                          ' ' +
                          this.data.tenant.phone
                        : '--'}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
            {this.renderPaymentInfo()}
            <View
              style={{
                width: width,
                backgroundColor: '#E5E7E9',
                height: 7,
                borderTopColor: '#D7DBDD',
                borderBottomColor: '#D7DBDD',
                borderTopWidth: 1,
                borderBottomWidth: 1,
              }}
            />
            <View style={{margin: 20}}>
              <Text style={styles.title}>{this.store.text.problems}</Text>
              <View
                style={{
                  marginTop: 20,
                  borderBottomWidth: 1,
                  borderBottomColor: colors.line2Color,
                }}>
                <Text
                  style={{
                    fontFamily: Fonts.ubuntuL,
                    fontSize: 17,
                    color: colors.line2Color,
                  }}>
                  {this.store.text.status}
                </Text>

                <Menu
                  name="status"
                  renderer={SlideInMenu}
                  onSelect={value => this.statusSelection(value)}>
                  <MenuTrigger
                    disabled={this.statusDisable}
                    style={{flexDirection: 'row', marginBottom: 5}}>
                    <View style={{flex: 0.8}}>
                      <Text
                        style={{
                          fontSize: 20,
                          color: 'black',
                          fontFamily: Fonts.ubuntuTh,
                        }}>
                        {this.statusTextReturn()}
                      </Text>
                    </View>
                    <View
                      style={{
                        flex: 0.2,
                        alignItems: 'flex-end',
                        marginRight: 10,
                      }}>
                      <Icon name="chevron-down" color={'black'} size={20} />
                    </View>
                  </MenuTrigger>
                  <MenuOptions
                    customStyles={{
                      optionText: {
                        margin: 5,
                        fontFamily: Fonts.ubuntu,
                        color: 'white',
                      },
                      optionWrapper: {
                        backgroundColor: colors.mainColor,
                        alignItems: 'center',
                      },
                    }}>
                    <MenuOption
                      value={'Processing'}
                      text={this.store.text.process}
                    />
                    <MenuOption
                      value={'Completed'}
                      text={this.store.text.closeFile}
                    />
                  </MenuOptions>
                </Menu>
              </View>
              <View
                style={{
                  marginTop: 20,
                  borderBottomWidth: 1,
                  borderBottomColor: colors.line2Color,
                }}>
                <Text
                  style={{
                    fontFamily: Fonts.ubuntuL,
                    fontSize: 17,
                    color: colors.line2Color,
                  }}>
                  {this.store.text.problems}
                </Text>

                <View style={{flexDirection: 'row', marginBottom: 5}}>
                  <View style={{flex: 0.8}}>
                    <TextInput
                      underlineColorAndroid="rgba(0,0,0,0)"
                      editable={this.editable}
                      style={{
                        fontSize: 20,
                        color: 'black',
                        fontFamily: Fonts.ubuntuTh,
                      }}
                      value={this.caseData.content}
                      onChangeText={text => {
                        this.caseData.content = text;
                      }}
                    />
                  </View>
                  <TouchableOpacity
                    disabled={!this.editable}
                    style={{flex: 0.2, alignItems: 'flex-end', marginRight: 10}}
                    onPress={() => {
                      this.caseData.content = '';
                    }}>
                    <Icon name="times-circle" color={'black'} size={20} solid />
                  </TouchableOpacity>
                </View>
              </View>

              {this.renderRemark()}
              <View
                style={{
                  width: width - 40,
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginTop: 40,
                  marginBottom: 40,
                }}>
                {this.buttonVisable ? (
                  <TouchableOpacity
                    onPress={() => {
                      this.caseData.log.push({content: ''});
                      if (this.props.navigation.state.params.type != 'create') {
                        this.buttonVisable = false;
                      }
                    }}>
                    <Text
                      style={{
                        fontSize: 20,
                        color: colors.mainColor,
                        fontFamily: Fonts.ubuntuTh,
                      }}>
                      {'+' + this.store.text.add}
                    </Text>
                  </TouchableOpacity>
                ) : (
                  <View></View>
                )}
              </View>
            </View>
          </KeyboardAwareScrollView>

          <Toast
            ref="toast"
            style={{backgroundColor: colors.mainColor}}
            position="bottom"
            positionValue={200}
            fadeInDuration={750}
            fadeOutDuration={2000}
            opacity={0.8}
            textStyle={{color: 'white'}}
          />
        </View>
      </MenuProvider>
    );
  }
}

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: {
    fontFamily: Fonts.ubuntuL,
    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: 20,
    color: 'black',
    fontFamily: Fonts.ubuntu,
  },

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