import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  View,
  TouchableOpacity,
  Alert,
  SafeAreaView,
  Text,
  TextInput,
} from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
var _ = require('lodash');
import Loading from '../../components/Loading';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import Icon2 from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import CustomLoginButton from '../../components/customLoginButton';
import Toast, { DURATION } from 'react-native-easy-toast';
import { colors } from '../../assets/styles/colors-theme';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const { SlideInMenu } = renderers;
import {
  CreditCardInput,
  LiteCreditCardInput,
} from 'react-native-credit-card-input';
//component
const areaData = [
  { label: '香港島', value: 0 },
  { label: '九龍', value: 1 },
  { label: '新界', value: 2 },
];

const area1Data = [
  { label: '中西區', value: 0 },
  { label: '灣仔區', value: 1 },
  { label: '東區', value: 2 },
  { label: '南區', value: 3 },
];
const area2Data = [
  { label: '深水埗區', value: 0 },
  { label: '油尖旺區', value: 1 },
  { label: '九龍城區', value: 2 },
  { label: '黃大仙區', value: 3 },
  { label: '觀塘區', value: 4 },
];
const area3Data = [
  { label: '葵青區', value: 0 },
  { label: '荃灣區', value: 1 },
  { label: '屯門區', value: 2 },
  { label: '元朗區', value: 3 },
  { label: '北區', value: 4 },
  { label: '大埔區', value: 5 },
  { label: '沙田區', value: 6 },
  { label: '西貢區', value: 7 },
  { label: '離島區', value: 8 },
];

// function
import { width, height } from '../../services/screen';
Icon.loadFont();

//const log = new Log()

const addressSetting = inject("appStore")(observer(class addressSetting extends React.Component {

  area1 = '';

  area2 = '';

  areaSelectIndex = null;

  area1Data = [];

  area2Data = [];

  address = '';


  addressData = {
    district: { id: null },
    address: '',
    mobile: '',
    receiver: '',
  };

  static navigationOptions = {
    drawerLabel: 'Account',
  };

  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      area1: observable,
      area2: observable,
      areaSelectIndex: observable,
      area1Data: observable,
      area2Data: observable,
      address: observable,
      addressData: observable,
    })
  }
  async componentWillMount() {
    await this.store.regions.map(async (items, index) => {
      if (!items.hasOwnProperty('parent')) {
        await this.area1Data.push(items);
      } else {
        if (this.store.addresses.length > 0) {
          if (items.parent.id == this.store.addresses[0].region.id) {
            console.log(items);
            await this.area2Data.push(items);
          }
        }
      }
    });

    if (this.store.addresses.length > 0) {
      this.area1 = this.store.addresses[0].region.name;
      this.area2 = this.store.addresses[0].district.name;
      this.addressData.district.id = this.store.addresses[0].district.id;
      this.addressData.receiver = this.store.addresses[0].receiver;
      this.addressData.mobile = this.store.addresses[0].mobile;
      this.addressData.address = this.store.addresses[0].address;
    }
  }

  async selectAction(value, which) {
    if (which) {
      this.area1 = value.name;
      this.area2 = '';
      this.addressData.district.id = null;
      var newArea2Data = [];
      await this.store.regions.map(async (items, index) => {
        if (items.hasOwnProperty('parent')) {
          if (items.parent.id === value.id) {
            console.log(items);
            await newArea2Data.push(items);
          }
        }
      });
      this.area2Data = newArea2Data;
    } else {
      this.addressData.district.id = value.id;
      this.area2 = value.name;
    }
  }

  saveAction() {
    if (this.addressData.mobile !== '') {
      if (this.addressData.receiver !== '') {
        if (this.addressData.address !== '') {
          if (this.area1 != '') {
            if (this.addressData.district.id != null) {
              //this.store.editAddress(_.cloneDeep(this.addressData), this);
              if (this.store.addresses.length > 0) {
                this.store.editAddress(
                  _.cloneDeep(this.addressData),
                  this.store.addresses[0].id,
                  this,
                );
              } else {
                this.store.addAddress(_.cloneDeep(this.addressData), this);
              }
            } else {
              this.refs.toast.show(this.store.text.pleaseSelectTheDistrict);
            }
          } else {
            this.refs.toast.show(this.store.text.pleaseSelectTheRegion);
          }
        } else {
          this.refs.toast.show(this.store.text.pleaseFillInTheAddress);
        }
      } else {
        this.refs.toast.show(this.store.text.pleaseFillInTheRecipientName);
      }
    } else {
      this.refs.toast.show(this.store.text.pleaseFillInTheRecipientMobile);
    }
  }

  render() {
    return (
      <MenuProvider
        style={{ flex: 1, backgroundColor: colors.bgc, alignItems: 'center' }}>
        <Loading loading={this.store.loading} />
        <View
          style={{
            height: 50,
            width: width,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: colors.mainColor,
          }}>
          <Text style={{ color: 'white', fontSize: 18 }}>
            {this.store.text.addressSetting}
          </Text>
        </View>
        <KeyboardAwareScrollView>
          <View style={{ flex: 1, alignItems: 'center' }}>
            <View style={{ marginTop: 20, width: width }}>
              <TouchableOpacity
                style={{
                  height: 60,
                  width: 60,
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.props.navigation.goBack();
                }}>
                <Icon
                  name="ios-arrow-back"
                  color={colors.mainColor}
                  size={40}
                />
              </TouchableOpacity>
            </View>

            <Menu
              name="area1"
              renderer={SlideInMenu}
              onSelect={value => {
                this.selectAction(value, true);
              }}>
              <MenuTrigger
                //disabled={!this.editable}
                style={{ flexDirection: 'row', marginBottom: 5 }}>
                <View
                  style={styles.inputTextView}
                // onPress={() => {
                //   this.area1 = '';
                //   this.area2 = '';
                //   this.areaData = ['香港島', '九龍', '新界'];
                //   this.picker.toggle();
                // }}
                >
                  <Text style={styles.inputTextTitleView}>
                    {this.store.text.district + ' '}
                  </Text>

                  <View style={{ flexDirection: 'row', marginBottom: 5 }}>
                    <View style={{ flex: 0.8 }}>
                      <Text
                        style={{
                          fontSize: 15,
                          color: 'black',
                          marginTop: 10,
                        }}>
                        {this.area1}
                      </Text>
                    </View>
                    <View
                      style={{
                        flex: 0.2,
                        alignItems: 'flex-end',
                        marginTop: 10,
                      }}>
                      <Icon2
                        name="chevron-down"
                        color={'black'}
                        size={20}
                        style={{ marginRight: 10 }}
                      />
                    </View>
                  </View>
                </View>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    color: 'white',
                    fontSize: 15,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {this.area1Data.map((obj, i) => {
                  return <MenuOption value={obj} text={obj.name} />;
                })}
              </MenuOptions>
            </Menu>
            <Menu
              name="area2"
              renderer={SlideInMenu}
              onSelect={value => {
                this.selectAction(value, false);
              }}>
              <MenuTrigger
                disabled={!this.areaSelectIndex == null}
                style={{ flexDirection: 'row', marginBottom: 5 }}>
                <View
                  style={styles.inputTextView}
                // onPress={() => {
                //   this.area1 = '';
                //   this.area2 = '';
                //   this.areaData = ['香港島', '九龍', '新界'];
                //   this.picker.toggle();
                // }}
                >
                  <Text style={styles.inputTextTitleView}>
                    {this.store.text.region + ' '}
                  </Text>

                  <View style={{ flexDirection: 'row', marginBottom: 5 }}>
                    <View style={{ flex: 0.8 }}>
                      <Text
                        style={{
                          fontSize: 15,
                          color: 'black',
                          marginTop: 10,
                        }}>
                        {this.area2}
                      </Text>
                    </View>
                    <View
                      style={{
                        flex: 0.2,
                        alignItems: 'flex-end',
                        marginTop: 10,
                      }}>
                      <Icon2
                        name="chevron-down"
                        color={'black'}
                        size={20}
                        style={{ marginRight: 10 }}
                      />
                    </View>
                  </View>
                </View>
              </MenuTrigger>
              <MenuOptions
                customStyles={{
                  optionText: {
                    margin: 5,
                    color: 'white',
                    fontSize: 15,
                  },
                  optionWrapper: {
                    backgroundColor: colors.mainColor,
                    alignItems: 'center',
                  },
                }}>
                {this.area2Data.map((obj, i) => {
                  return <MenuOption value={obj} text={obj.name} />;
                })}
              </MenuOptions>
            </Menu>

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

              <View style={{ flexDirection: 'row', marginBottom: 5 }}>
                <View style={{ flex: 1 }}>
                  <TextInput
                    style={{
                      fontSize: 15,
                      color: 'black',
                      marginTop: 10,
                      marginBottom: Platform.OS === 'ios' ? 4 : 0,
                      paddingVertical: 0,
                    }}
                    value={this.addressData.address}
                    onChangeText={text => (this.addressData.address = text)}
                  />
                </View>
              </View>
            </View>

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

              <View style={{ flexDirection: 'row', marginBottom: 5 }}>
                <View style={{ flex: 1 }}>
                  <TextInput
                    style={{
                      fontSize: 15,
                      color: 'black',
                      marginTop: 10,
                      marginBottom: Platform.OS === 'ios' ? 4 : 0,
                      paddingVertical: 0,
                    }}
                    value={this.addressData.receiver}
                    onChangeText={text => (this.addressData.receiver = text)}
                  />
                </View>
              </View>
            </View>
            <View style={styles.inputTextView}>
              <Text style={styles.inputTextTitleView}>
                {this.store.text.TheRecipientPhone + ' '}
              </Text>

              <View style={{ flexDirection: 'row', marginBottom: 5 }}>
                <View style={{ flex: 1 }}>
                  <TextInput
                    style={{
                      fontSize: 15,
                      color: 'black',
                      marginTop: 10,
                      marginBottom: Platform.OS === 'ios' ? 4 : 0,
                      paddingVertical: 0,

                    }}
                    value={this.addressData.mobile}
                    onChangeText={text => (this.addressData.mobile = text)}
                  />
                </View>
              </View>
            </View>
            <View style={{ marginTop: 30 }}>
              <CustomLoginButton
                title={this.store.text.save}
                onPress={() => {
                  this.saveAction();
                }}
              />
            </View>
          </View>
        </KeyboardAwareScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="center"
          positionValue={100}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </MenuProvider>
    );
  }
}))

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: 'white',
  },

  button: {
    marginTop: 20,
    width: width,
    height: 60,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.statusBarColor,
  },
  inputTextView: {
    width: width - 40,
    marginTop: 20,
    borderBottomWidth: 1,
    borderBottomColor: colors.line2Color,
    height: 50,
  },
  inputTextTitleView: {
    fontSize: 14,
    color: colors.line2Color,
  },
  title: {
    fontSize: 17,
    marginTop: 20,
  },
  subtitle: {
    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,

    fontSize: 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
  },
});
export default addressSetting
