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';
import {uploadImage} from '../../../apis/Functions/Upload';
import {TYPE, showAlert} from '../../../components/DropdownAlert';

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 = (photo, body) => {
    const data = new FormData();
    data.append('image_file', {
      name: 'sign_img.jpg',
      type: 'image/jpg',
      uri: Platform.OS === 'android' ? photo : photo.replace('file://', ''),
    });
    Object.keys(body).forEach((key) => {
      data.append(key, body[key]);
    });
    console.log('Data', data);

    return data;
  };

  const onPress = async () => {
    props.showLoading();
    var async = require('async');
    const titles = [
      I18n.t('CardType').toLowerCase(),
      I18n.t('IdentityCardFrontPhoto'),
      I18n.t('IdentityCardBackPhoto'),
      I18n.t('SignPhoto').toLowerCase(),
    ];
    const index = checkFormatArray([type, urlBack, urlFont, urlSign]);
    if (index === true) {
      async.parallel(
        [
          async function (callback) {
            const res = await uploadImage(
              createFormData(urlFont, {
                scope: 'VERIFY_USER',
                field_name: 'identity_before',
                platform: Platform.OS,
              }),
            );
            callback(null, res);
          },
          async function (callback) {
            const res = await uploadImage(
              createFormData(urlBack, {
                scope: 'VERIFY_USER',
                field_name: 'identity_after',
                platform: Platform.OS,
              }),
            );

            callback(null, res);
          },
          async function (callback) {
            const res = await uploadImage(
              createFormData(urlSign, {
                scope: 'VERIFY_USER',
                field_name: 'sign_img',
                platform: Platform.OS,
              }),
            );

            callback(null, res);
          },
        ],
        async function (err, results) {
          if (
            results[0].status == 200 &&
            results[1].status == 200 &&
            results[2].status == 200
          ) {
            if (
              results[0].data.data.path &&
              results[1].data.data.path &&
              results[2].data.data.path
            ) {
              const data = {
                card_type: type.value,
                uid: props.user.uid,
                ...props.route.params,
                mode: 'TEST',
                identity_before_path: results[0].data.data.path,
                identity_after_path: results[1].data.data.path,
                sign_image_path: results[2].data.data.path,
              };
              const res = await verifyAccountApi(data);
              props.hideLoading();
              if (res?.status == 200 && res.data) {
                if (res.data.code == 200) {
                  showAlert(
                    TYPE.SUCCESS,
                    I18n.t('Notification'),
                    res.data.message,
                  );
                  props.saveUserToRedux(res.data.data);
                  props.navigation.popToTop();
                } else {
                  props.hideLoading();
                  showAlert(
                    TYPE.ERROR,
                    I18n.t('Notification'),
                    res.data.message,
                  );
                }
              } else {
                props.hideLoading();
                showAlert(
                  TYPE.ERROR,
                  I18n.t('Notification'),
                  I18n.t('UploadImageFail'),
                );
              }
            }
          }
        },
      );
    } else {
      props.hideLoading();
      showAlert(
        TYPE.ERROR,
        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);