import React, {useState, useEffect} from 'react';
import ConfirmSmartOTPView from './ConfirmSmartOTPView';
import {updateOTPApiSmart} from '../../../apis/Functions/users';
import {showAlert, TYPE} from '../../../components/DropdownAlert';
import {connect} from 'react-redux';
import {hideLoading, showLoading} from '../../../actions/loadingAction';
import I18n from '../../../helper/i18/i18n';
import {SMARTOTPCONFIG} from '../../../routers/ScreenNames';
import {useNavigation} from '@react-navigation/native';

const ConfirmChangeSmartOTP = (props) => {
  const [firstNumber, setFirstNumber] = useState(null);
  const [secondsNumber, setSecondsNumber] = useState(null);
  const [thirdNumber, setThirdNumber] = useState(null);
  const [fourNumber, setFourNumber] = useState(null);
  const navigation = useNavigation();
  useEffect(() => {
    if (fourNumber) {
      onCheckPINSmartOTPPin();
    }
  }, [fourNumber]);
  const onNumberPress = (number) => {
    if (!firstNumber) {
      setFirstNumber(number.toString());
    } else if (!secondsNumber) {
      setSecondsNumber(number.toString());
    } else if (!thirdNumber) {
      setThirdNumber(number.toString());
    } else if (!fourNumber) {
      setFourNumber(number.toString());
    }
  };

  const onCheckPINSmartOTPPin = async () => {
    let pinCode = `${firstNumber}${secondsNumber}${thirdNumber}${fourNumber}`;
    const res = await updateOTPApiSmart({
      platform: Platform.OS,
      password: props.route.params.pre_otp,
      password_confirmation: pinCode,
      old_password: props.route.params.old_password,
    });
    if (res.data.code == 200) {
      showAlert(TYPE.SUCCESS, I18n.t('Notification'), res.data.message);
      navigation.reset({
        index: 1,
        routes: [{name: SMARTOTPCONFIG}],
      });
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
      setFirstNumber(null);
      setSecondsNumber(null);
      setThirdNumber(null);
      setFourNumber(null);
    }
  };
  const onDeletePress = () => {
    if (fourNumber) {
      setFourNumber(null);
    } else if (thirdNumber) {
      setThirdNumber(null);
    } else if (secondsNumber) {
      setSecondsNumber(null);
    } else if (firstNumber) {
      setFirstNumber(null);
    }
  };

  return (
    <ConfirmSmartOTPView
      firstNumber={firstNumber}
      secondsNumber={secondsNumber}
      thirdNumber={thirdNumber}
      fourNumber={fourNumber}
      onNumberPress={onNumberPress}
      onDeletePress={onDeletePress}
    />
  );
};
const mapStateToProps = (state) => {
  return {
    user: state.userReducer,
  };
};

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