import React from 'react';
import {
  View,
  TextInput,
  Text,
  Image,
  TouchableOpacity,
  BackHandler,
  Keyboard,
  Platform,
  StatusBar,
  Modal
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import styles from './../Profile/Styles/ProfileStyle';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import ImagePicker from 'react-native-image-crop-picker';
import Icon from 'react-native-vector-icons/Ionicons';
import {
  Container,
  Content,
  Header,
  Loader,
  ImageX
} from './../../../components';
import { Images } from './../../../theme';
import {
  updateProfileRequest,
  getProfileRequest,
  getCountryListRequest
} from './../../../actions';
import { ApiConfig } from 'src/config';
import { FlatList } from 'react-native-gesture-handler';

export interface Props {
  navigation: any;
  navigationProps: any;
  updateProfile: any;
  user: any;
  profile: any;
  getProfile: any;
  loading: any;
  data: any;
  getCountryList: any;
  countryList: any;
}

interface State {
  selected?: any;
  status?: boolean;
  imageBinary?: any;
  profileState: any;
  firstName: any;
  lastName: any;
  email: any;
  mobileNo: any;
  address1: any;
  address2: any;
  city: any;
  zipcode: any;
  state: any;
  country: any;
  imagePath: any;
  isImageSelected: boolean;
  modalVisible: boolean;
  data: any;
  selectCountryId: any;
  selectedCountry:any;
  isNew:any;
}
class ProfileScreen extends React.Component<Props, State> {
  firstNameRef: any;
  lastNameRef: any;
  emailRef: any;
  mobileNoRef: any;
  address1Ref: any;
  address2Ref: any;
  ciryRef: any;
  zipCodeRef: any;
  stateRef: any;
  countryRef: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      imageBinary: null,
      profileState: {},
      firstName: '',
      lastName: '',
      email: '',
      mobileNo: '',
      address1: '',
      address2: '',
      city: '',
      zipcode: '',
      state: '',
      country: ' ',
      imagePath: null,
      isImageSelected: false,
      modalVisible: false,
      data: '',
      selectCountryId: 1,
      selectedCountry:'',
      isNew:false
    };
  }
  setModalVisible(visible: any) {
    this.setState({ modalVisible: visible });
  }

  componentDidMount = () => {
    const { getProfile, profile, getCountryList } = this.props;
    getProfile();
    getCountryList();
    if (profile.first_name) {
      this.setState({
        firstName: profile.first_name,
        lastName: profile.last_name,
        email: profile.email,
        mobileNo: profile.phone
      });
      if (profile.address && profile.address.id) {
        let address = profile.address;

        this.setState({
          address1: address.address_1,
          address2: address.address_2,
          city: address.city,
          zipcode: address.zip && address.zip.toString(),
          state: address.state,
          country:address.country.name
        });
      }
    }
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
  };

  componentWillUnmount = () => {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
  };
  country_IDModal = () => {
    const { countryList } = this.props;
    return (
      <Modal
        animationType="slide"
        transparent={true}
        visible={this.state.modalVisible}
        onRequestClose={() => {
          this.setModalVisible(false);
        }}>
        <TouchableOpacity
          activeOpacity={1}
          onPress={() => this.setModalVisible(false)}
          style={styles.modalStyle}>
          <TouchableOpacity activeOpacity={1} style={styles.modalView}>
            <View style={styles.firstmodalView}>
              <Text style={styles.textStyle}>Select Country Name</Text>
              <TouchableOpacity
                style={styles.closeBtn}
                onPress={() => {
                  this.setModalVisible(false);
                }}>
                <Icon name={'ios-close'} style={styles.inputiconmodel} />
              </TouchableOpacity>
            </View>

            <View style={styles.modalTextView}>
              <FlatList
               showsVerticalScrollIndicator={false}
                data={countryList}
                style={styles.flatlist}
                renderItem={({ item}:any) => (
                  <TouchableOpacity
                    onPress={() => {
                      this.setState({ selectCountryId: item.id ,selectedCountry:item.name,isNew:true});
                      this.setModalVisible(false);
                    }}>
                    <Text style={styles.item}>{item.name}</Text>
                    <View style={styles.borderToLine} />
                  </TouchableOpacity>
                )}
              />
            </View>
          </TouchableOpacity>
        </TouchableOpacity>
      </Modal>
    );
  };

  shouldComponentUpdate = (nextProps: any) => {
    const { profile } = this.props;
    if (profile !== nextProps.profile) {
      this.setState({ profileState: nextProps.profile || {} });
      if (nextProps.profile && nextProps.profile.first_name) {
        this.setState({
          firstName: nextProps.profile.first_name,
          lastName: nextProps.profile.last_name,
          email: nextProps.profile.email,
          mobileNo: nextProps.profile.phone
        });
        if (nextProps.profile.address && nextProps.profile.address.id) {
          let address = nextProps.profile.address;
          this.setState({
            address1: address.address_1,
            address2: address.address_2,
            city: address.city,
            zipcode: address.zip && address.zip.toString(),
            state: address.state,
            country:address.country.name
          });
        }
      }
    }
    return true;
  };

  backHandler = () => {
    const { navigation } = this.props;
    return navigation.goBack();
  };

  selectImage = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      includeBase64: true
    }).then((image: any) => {
     this.setState({
        imageBinary: image.data,
        imagePath: image.path,
        isImageSelected: true
      });
    });
  };

  saveData = () => {
    const { updateProfile, user } = this.props;
    const {
      imageBinary,
      firstName,
      lastName,
      email,
      mobileNo,
      address1,
      address2,
      city,
      zipcode,
      state,
      country,
      imagePath,
      isImageSelected,
      selectCountryId
    } = this.state;
    let params = {
      id: user.id,
      member_id: user.member_id,
      first_name: firstName,
      last_name: lastName,
      email: email,
      // email_verified_at: email,
      phone: mobileNo,
      // image: imagePath,
      address_1: address1,
      address_2: address2,
      state: state,
      city: city,
      zip: zipcode,
      country_id:selectCountryId
    };
    const currentTime = new Date().getTime();
    var photo = {
      uri: imagePath,
      type: 'image/jpeg',
      name: currentTime + '_' + params.id + '.jpg'
    };

    const formData = new FormData();
    formData.append('image', isImageSelected == true ? photo : '');
    formData.append('id', params.id);
    formData.append('first_name', params.first_name);
    formData.append('last_name', params.last_name);
    formData.append('email', params.email);
    formData.append('phone', params.phone);
    formData.append('address_1', params.address_1);
    formData.append('address_2', params.address_2);
    formData.append('state', params.state);
    formData.append('city', params.city);
    formData.append('zip', params.zip);
    formData.append('country_id', params.country_id);
    updateProfile(formData);
  };

  moveFocus = (key: any) => {
    let toFocus = null;

    switch (key) {
      case 'firstNameRef':
        toFocus = this.lastNameRef.focus();
        break;
      case 'lastNameRef':
        toFocus = this.emailRef.focus();
        break;
      case 'emailRef':
        toFocus = this.mobileNoRef.focus();
        break;
      case 'mobileNoRef':
        toFocus = this.address1Ref.focus();
        break;
      case 'address1Ref':
        toFocus = this.address2Ref.focus();
        break;
      case 'address2Ref':
        toFocus = this.ciryRef.focus();
        break;
      case 'ciryRef':
        toFocus = this.zipCodeRef.focus();
        break;
      case 'zipCodeRef':
        toFocus = this.stateRef.focus();
        break;
      case 'stateRef':
        toFocus = this.address1Ref.focus();
        break;
      default:
        toFocus = null;
    }
    return toFocus;
  };

  render() {
    const { profile, navigation, loading } = this.props;
    const {
      firstName,
      lastName,
      email,
      mobileNo,
      address1,
      address2,
      city,
      zipcode,
      state,
      country,
      imagePath,
      selectedCountry,
      isNew
    } = this.state;

    return (
      <>
        <Header
          isTransparent
          hasHeaderThin
          profileBackImage
          hasBackBtn
          navigation={navigation}
          rightBtn={
            <TouchableOpacity onPress={() => this.saveData()}>
              <Text style={styles.saveBtnTxt}>Save</Text>
            </TouchableOpacity>
          }
        />

        <View style={styles.profilePicView}>
          <ImageX
            imageStyle={styles.profilePic}
            // defaultImageRoundShape
            source={{
              uri: imagePath ? 'file://' + imagePath : profile.image_path
            }}
            defaultText={
              (firstName && firstName.charAt(0)) +
              ' ' +
              (lastName && lastName.charAt(0))
            }
            style={styles.profilePic}
          />

          <TouchableOpacity
            style={styles.changeProfilePicBtn}
            onPress={() => this.selectImage()}>
            <Ionicons name="ios-reverse-camera" style={styles.cameraIcon} />
          </TouchableOpacity>
        </View>
        <Text style={styles.profileName}>
          {profile.first_name + ' ' + profile.last_name}
        </Text>
        <Container
          transparentStatusBar
          safeAreaView={Platform.OS === 'ios' ? false : false}>
          <StatusBar barStyle="dark-content" backgroundColor="transparent" />
          <Content>
            <View style={styles.viewStyle}>
              <View style={styles.titleContainer}>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
                <Text style={styles.titleTxt}>Primary Details</Text>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
              </View>

              <View style={styles.halfContainer}>
                <View style={styles.halfInnerContainer}>
                  <Text style={styles.labelTxt}>First Name:</Text>
                  <TextInput
                    ref={component => (this.firstNameRef = component)}
                    placeholder={'First Name '}
                    style={styles.halfValueTxt}
                    value={firstName}
                    returnKeyType={'next'}
                    onChangeText={res => this.setState({ firstName: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('firstNameRef');
                    }}
                  />
                </View>
                <View style={styles.halfInnerContainer}>
                  <Text style={styles.labelTxt}>Last Name:</Text>
                  <TextInput
                    ref={component => (this.lastNameRef = component)}
                    placeholder={'Last Name'}
                    style={styles.halfValueTxt}
                    value={lastName}
                    returnKeyType={'next'}
                    onChangeText={res => this.setState({ lastName: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('lastNameRef');
                    }}
                  />
                </View>
              </View>

              <View style={styles.fullContainer}>
                <Text style={styles.labelTxt}>E-mail Address:</Text>
                <TextInput
                  editable={false}
                  ref={component => (this.emailRef = component)}
                  placeholder={'E-mail Address'}
                  style={styles.fullValueTxt}
                  value={email}
                  returnKeyType={'next'}
                  onChangeText={res => this.setState({ email: res })}
                  onSubmitEditing={() => {
                    this.moveFocus('emailRef');
                  }}
                />
              </View>
              <View style={styles.fullContainer}>
                <Text style={styles.labelTxt}>Mobile No:</Text>
                <View style={styles.countryCodeTxtView}>
                  <Text style={styles.countryCodeTxt}>(+91)</Text>
                  <TextInput
                    ref={component => (this.mobileNoRef = component)}
                    style={styles.fullValueCountryCodeTxt}
                    placeholder={'Mobile No'}
                    keyboardType={'phone-pad'}
                    value={mobileNo}
                    returnKeyType={'done'}
                    returnKeyLabel={'next'}
                    onChangeText={res => this.setState({ mobileNo: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('mobileNoRef');
                    }}
                  />
                </View>
              </View>

              <View style={styles.titleContainer}>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
                <Text style={styles.titleTxt}>Address Details</Text>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
              </View>

              <View style={styles.fullContainer}>
                <Text style={styles.labelTxt}>Address 1:</Text>
                <TextInput
                  ref={component => (this.address1Ref = component)}
                  placeholder={'Address 1'}
                  style={styles.fullValueTxt}
                  value={address1}
                  returnKeyType={'next'}
                  onChangeText={res => this.setState({ address1: res })}
                  onSubmitEditing={() => {
                    this.moveFocus('address1Ref');
                  }}
                />
              </View>
              <View style={styles.fullContainer}>
                <Text style={styles.labelTxt}>Address 2:</Text>
                <TextInput
                  placeholder={'Address 2'}
                  ref={component => (this.address2Ref = component)}
                  style={styles.fullValueTxt}
                  value={address2}
                  returnKeyType={'next'}
                  onChangeText={res => this.setState({ address2: res })}
                  onSubmitEditing={() => {
                    this.moveFocus('address2Ref');
                  }}
                />
              </View>

              <View style={styles.halfContainer}>
                <View style={styles.halfInnerContainer}>
                  <Text style={styles.labelTxt}>City:</Text>
                  <TextInput
                    placeholder={'City'}
                    ref={component => (this.ciryRef = component)}
                    style={styles.halfValueTxt}
                    value={city}
                    returnKeyType={'next'}
                    onChangeText={res => this.setState({ city: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('ciryRef');
                    }}
                  />
                </View>
                <View style={styles.viewStyle08}>
                  <Text style={styles.labelTxt}>Zip(pin) Code:</Text>
                  <TextInput
                    ref={component => (this.zipCodeRef = component)}
                    style={styles.halfValueTxt}
                    placeholder={'Zip(pin) Code'}
                    value={zipcode}
                    returnKeyType={'done'}
                    keyboardType={'phone-pad'}
                    onChangeText={res => this.setState({ zipcode: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('zipCodeRef');
                    }}
                  />
                </View>
              </View>

              <View style={styles.halfContainer}>
                <View style={styles.halfInnerContainer}>
                  <Text style={styles.labelTxt}>State:</Text>
                  <TextInput
                    placeholder={'State'}
                    ref={component => (this.stateRef = component)}
                    style={styles.halfValueTxt}
                    value={state}
                    returnKeyType={'next'}
                    onChangeText={res => this.setState({ state: res })}
                    onSubmitEditing={() => {
                      this.moveFocus('stateRef');
                    }}
                  />
                </View>
                <TouchableOpacity
                  onPress={() => {
                    this.setModalVisible(true);
                  }}
                  style={styles.viewStyle08}>
                  <Text style={styles.labelTxt}>Country:</Text>
                  <TextInput
                    editable={false}
                    numberOfLines={1}
                    placeholder={'Country'}
                    ref={component => (this.countryRef = component)}
                    style={styles.halfValuTestTxt}
                     value={isNew==false?country:selectedCountry}
                    returnKeyType={'next'}
                    onChangeText={res => this.setState({ country: res })}
                    // onSubmitEditing={() => {
                    //   Keyboard.dismiss();
                    // }}
                  />
                </TouchableOpacity>
              </View>
            </View>
            {this.country_IDModal()}
          </Content>
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}

function mapStateToProps({ user, general }: any) {
  return {
    loading: user.loading || false,
    user: (user.user && user.user.user) || {},
    profile: user.profile || {},
    countryList: general.countryList
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      updateProfile: updateProfileRequest,
      getProfile: getProfileRequest,
      getCountryList: getCountryListRequest
    },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ProfileScreen);
