import React, {Component, useEffect, useState} from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';
import HeaderBack from '../../../components/Header/HeaderBack';
import {walletDeposit} from '../../../apis/Functions/Deposit';
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import {getFontXD, HEIGHTXD, WIDTHXD} from '../../../Config/Functions';
import R from '.././../../assets/R';
import {
  verifyOTPApi,
  registorApi,
  getOTPApi,
} from '../../../apis/Functions/users';
import {useNavigation} from '@react-navigation/native';
import I18n from '../../../helper/i18/i18n';
import AppText from '../../../components/AppText';
import {widthDraw, getListWidthDraw} from '../../../apis/Functions/Widthdraw';
import {showLoading, hideLoading} from '../../../actions/loadingAction';
import {connect} from 'react-redux';
import {TABNAVIGATOR} from '../../../routers/ScreenNames';
import {showAlert, TYPE} from '../../../components/DropdownAlert';
import CountDown from '../../../components/CountDown';

const CELL_COUNT = 4;

const ConfirmOTP = (propsa) => {
  const [value, setValue] = useState('');

  const [isReset, setReset] = useState(false);

  const navigate = useNavigation();

  const ref = useBlurOnFulfill({value, cellCount: CELL_COUNT});
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({
    value,
    setValue,
  });
  console.log('Type', propsa.route.params.type);

  const confirm = async () => {
    if (!value) {
      showAlert(TYPE.WARN, I18n.t('Notification'), I18n.t('EnterOTPRequest'));
    } else if (value.length != 4) {
      showAlert(TYPE.WARN, I18n.t('Notification'), I18n.t('OTPInvalid'));
    } else {
      propsa.showLoading();
      let res1;
      if (propsa.route.params.type == 'DEPOSIT') {
        res1 = await verifyOTPApi({
          platform: Platform.OS,
          receiver_name: propsa.user.email,
          otp: value,
          type: 'CUSTOMER_REQUEST_DEPOSIT',
        });
      } else {
        res1 = await verifyOTPApi({
          platform: Platform.OS,
          receiver_name: propsa.user.email,
          otp: value,
          type: 'CUSTOMER_REQUEST_DEPOSIT',
        });
      }
      if (res1.data.code == 200) {
        let res;

        if (propsa.route.params.type == 'DEPOSIT') {
          const {amount, notes} = propsa.route.params;

          res = await walletDeposit({
            amount,
            platform: Platform.OS,
            notes,
            fee: 0,
          });
        } else {
          const {src, receiving_account, amount, notes} = propsa.route.params;
          res = await widthDraw({
            src,
            receiving_account,
            amount,
            platform: Platform.OS,
            notes,
            fee: 0,
          });
        }

        propsa.hideLoading();
        if (res.data.code == 200) {
          setTimeout(() => {
            showAlert(TYPE.SUCCESS, I18n.t('Notification'), res.data.message);

            navigate.navigate(TABNAVIGATOR);
          }, 500);
        } else {
          showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
        }
      } else {
        showAlert(TYPE.ERROR, I18n.t('Notification'), res1.data.message);
      }

      propsa.hideLoading();
    }
  };

  const getOTP = async () => {
    let res;
    propsa.showLoading();
    if (propsa.route.params.type == 'DEPOSIT') {
      res = await getOTPApi({
        platform: Platform.OS,
        otp_by: propsa.user.email,
        type: 'CUSTOMER_REQUEST_DEPOSIT',
      });
    } else {
      res = await getOTPApi({
        platform: Platform.OS,
        otp_by: propsa.user.email,
        type: 'REQUEST_WITHDRAW',
      });
    }
    propsa.hideLoading();
    if (res.data.code == 200) {
      setReset(!isReset);
      showAlert(TYPE.SUCCESS, I18n.t('Notification'), res.data.message);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };

  return (
    <View style={{flex: 1}}>
      <HeaderBack title={'VerifyOTP'} />
      <View style={styles.container}>
        <View style={{height: 20}} />
        <View style={styles.wrap}>
          <AppText i18nKey={'Verify_code'} style={styles.txtTitle} />
          <View style={styles.containerCode}>
            <CodeField
              ref={ref}
              {...props}
              value={value}
              onChangeText={setValue}
              cellCount={CELL_COUNT}
              rootStyle={styles.codeFieldRoot}
              keyboardType="number-pad"
              textContentType="oneTimeCode"
              renderCell={({index, symbol, isFocused}) => (
                <View
                  onLayout={getCellOnLayoutHandler(index)}
                  key={index}
                  style={[styles.cellRoot, isFocused && styles.focusCell]}>
                  <Text style={styles.cellText}>
                    {symbol || (isFocused ? <Cursor /> : null)}
                  </Text>
                </View>
              )}
            />
          </View>
        </View>
      </View>
      <View style={styles.footer}>
        <TouchableOpacity onPress={confirm} style={styles.btn}>
          <AppText i18nKey={'Continue'} style={styles.txtBtn} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.wrapFooter} onPress={getOTP}>
          <Text style={styles.txtNote}>{I18n.t('OTPValidFiveMinute')}</Text>

          <AppText i18nKey={'Re_send'} style={styles.txtSend} />
        </TouchableOpacity>
        <CountDown isReset={isReset} />
      </View>
    </View>
  );
};

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

    paddingVertical: 20,
  },
  footer: {
    height: 200,
    justifyContent: 'center',
    alignItems: 'center',
  },
  wrap: {
    flex: 1,
    paddingTop: 30,
    alignItems: 'center',
    width: '100%',
    paddingHorizontal: 50,
  },
  containerCode: {
    height: 50,

    width: '100%',
    marginTop: 30,
  },
  codeFieldRoot: {
    marginTop: 20,
  },

  focusCell: {
    borderColor: '#000',
  },
  cellRoot: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
  },
  cellText: {
    color: '#000',
    fontSize: 36,
    textAlign: 'center',
  },
  focusCell: {
    borderBottomColor: '#007AFF',
    borderBottomWidth: 2,
  },
  txtTitle: {
    fontSize: getFontXD(52),
    color: '#979797',
  },
  btn: {
    width: WIDTHXD(521),
    height: HEIGHTXD(120),
    borderRadius: 15,
    backgroundColor: '#1C6AF6',
    justifyContent: 'center',
    alignItems: 'center',
  },
  txtBtn: {
    color: R.colors.white,
    fontSize: getFontXD(52),
    textTransform: 'uppercase',
  },
  txtSend: {
    fontSize: getFontXD(42),
    color: '#1C6AF6',
  },
  wrapFooter: {
    marginTop: 30,
    flexDirection: 'row',
    alignItems: 'center',
  },
  txtNote: {
    color: '#A2A2A2',
    fontSize: getFontXD(42),
    fontStyle: 'italic',
  },
});

const mapStateToProps = (state) => {
  return {
    user: state.userReducer,
  };
};

export default connect(mapStateToProps, {showLoading, hideLoading})(ConfirmOTP);