import React, {useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  ScrollView,
  Platform,
  Dimensions,
  TouchableWithoutFeedback,
  Keyboard,
} from 'react-native';
import Button from '../../../components/Button';
import PickerImgUni from '../../../components/Picker/PickerImgUni';
import R from '../../../assets/R';
import TextField from '../../../components/Input/TextField';
import {connect} from 'react-redux';
import {showLoading, hideLoading} from '../../../actions/loadingAction';
import {
  checkFormatArray,
  getFontXD,
  convertTime,
} from '../../../Config/Functions';
import {verifyAccountApi} from '../../../apis/Functions/users';
import PickerDate from '../../../components/Picker/PickerDate';
import PickerItem from '../../../components/Picker/PickerItem';
import {saveUserToRedux} from '../../../actions/users';
import I18n from '../../../helper/i18/i18n';

const {width} = Dimensions.get('window');

const dataType = [
  {
    value: '1',
    name: I18n.t('IdentityCard'),
  },
  {
    value: '2',
    name: I18n.t('Passport'),
  },
  {
    value: '3',
    name: I18n.t('CitizenIdentification'),
  },
];

const Profile = (props) => {
  const [urlFont, setUrlFont] = useState(props.user.identity_before);
  const [urlBack, setUrlBack] = useState(props.user.identity_after);
  const [urlSign, setUrlSign] = useState(props.user.sign_img);

  const [type, setType] = useState();

  const createFormData = (identity_after, identity_before, sign_img, body) => {
    const data = new FormData();

    data.append('identity_after', {
      name: 'identity_after.jpg',
      type: 'image/jpg',
      uri:
        Platform.OS === 'android'
          ? identity_after
          : identity_after.replace('file://', ''),
    });

    data.append('identity_before', {
      name: 'identity_before.jpg',
      type: 'image/jpg',
      uri:
        Platform.OS === 'android'
          ? identity_before
          : identity_before.replace('file://', ''),
    });

    data.append('sign_image', {
      name: 'sign_img.jpg',
      type: 'image/jpg',
      uri:
        Platform.OS === 'android' ? sign_img : sign_img.replace('file://', ''),
    });

    Object.keys(body).forEach((key) => {
      data.append(key, body[key]);
    });
    return data;
  };

  const onPress = async () => {
    const titles = [
      I18n.t('CardType').toLowerCase(),
      I18n.t('IdentityCardFrontPhoto'),
      I18n.t('IdentityCardBackPhoto'),
      I18n.t('SignPhoto').toLowerCase(),
    ];
    const index = checkFormatArray([type, urlFont, urlBack, urlSign]);
    if (index === true) {
      const data = createFormData(urlFont, urlBack, urlSign, {
        card_type: type.value,
        uid: props.user.uid,
        ...props.route.params,
      });
      props.showLoading();
      const res = await verifyAccountApi(data);
      props.hideLoading();
      console.log(res);
      if (res.data.code == 200) {
        setTimeout(() => {
          props.saveUserToRedux(res.data.data);
          Alert.alert(I18n.t('Notification'), res.data.message);
          props.navigation.popToTop();
        }, 500);
      } else {
        setTimeout(() => {
          Alert.alert(I18n.t('Notification'), res.data.message);
        }, 500);
      }
    } else {
      Alert.alert(
        I18n.t('Notification'),
        I18n.t('Please_fill_in') + titles[index],
      );
    }
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.Os === 'ios' ? 'padding' : 'height'}
      style={{flex: 1}}
      keyboardVerticalOffset={-50}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <ScrollView style={{flex: 1}} showsVerticalScrollIndicator={false}>
          <View
            style={{
              flex: 1,
              paddingHorizontal: 10,
              paddingTop: 10,
            }}>
            <Text
              style={{
                fontSize: getFontXD(42),
                color: R.colors.color777,
              }}>
              {I18n.t('CardType')}
            </Text>
            <PickerItem
              width={width - 20}
              data={dataType}
              onValueChange={(value, items) => {
                setType(items);
              }}
            />
            {/*
          <TextField
            isNumber={true}
            title={'Số thẻ'}
            onChangeText={(val) => setCMND(val)}
          />
          <PickerDate
            value={date_range}
            onValueChange={(val) => setDate_range(val)}
            title={'Ngày cấp'}
          /> */}
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                flex: 1,
              }}>
              <PickerImgUni
                uriImage={urlFont}
                onSelectImg={(path) => setUrlFont(path)}
                title={I18n.t('IdentityCardFrontPhoto')}
              />
              <PickerImgUni
                uriImage={urlBack}
                onSelectImg={(path) => setUrlBack(path)}
                title={I18n.t('IdentityCardBackPhoto')}
              />
              <PickerImgUni
                uriImage={urlSign}
                onSelectImg={(path) => setUrlSign(path)}
                title={I18n.t('SignPhoto')}
              />
            </View>
          </View>
          <View style={styles.btnSend}>
            <Button title={I18n.t('Confirm')} onClick={onPress} />
          </View>
        </ScrollView>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  btnSend: {
    width: '100%',
    marginVertical: 30,
  },
  btnNext: {
    borderRadius: 30,
    backgroundColor: '#1473E6',
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 20,
    alignSelf: 'flex-end',
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.15,
    shadowRadius: 1.84,
  },
});

const mapStateToProps = (state) => {
  return {
    user: state.userReducer,
  };
};
export default connect(mapStateToProps, {
  showLoading,
  hideLoading,
  saveUserToRedux,
})(Profile);
