import React, {useState, useEffect} from 'react';
import ConfirmCreateView from './ConfirmCreateView';
import {verifyStoreOTPApiSmart} 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 {useNavigation} from '@react-navigation/native';
import {
  CONFIRMCHANGESMARTOTP,
  TABNAVIGATOR,
} from '../../../routers/ScreenNames';

const EnterPasswordSmartOTP = (props) => {
  const navigation = useNavigation();
  const [firstNumber, setFirstNumber] = useState(null);
  const [secondsNumber, setSecondsNumber] = useState(null);
  const [thirdNumber, setThirdNumber] = useState(null);
  const [fourNumber, setFourNumber] = useState(null);
  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}`;
    setFirstNumber(null);
    setSecondsNumber(null);
    setThirdNumber(null);
    setFourNumber(null);
    props.showLoading();
    const res = await verifyStoreOTPApiSmart({
      platform: Platform.OS,
      password: props.route.params.password,
      password_confirmation: props.route.params.password_confirmation,
      otp: pinCode,
      type: 'CREATE_OTP_PASSWORD',
    });
    props.hideLoading();
    if (res.data.code == 200) {
      showAlert(TYPE.SUCCESS, I18n.t('Notification'), res.data.message);
      navigation.navigate(TABNAVIGATOR);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };
  const onDeletePress = () => {
    if (fourNumber) {
      setFourNumber(null);
    } else if (thirdNumber) {
      setThirdNumber(null);
    } else if (secondsNumber) {
      setSecondsNumber(null);
    } else if (firstNumber) {
      setFirstNumber(null);
    }
  };

  return (
    <ConfirmCreateView
      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})(
  EnterPasswordSmartOTP,
);
