import { useState } from 'react';
import authService from '../services/authService';
import { useNavigate } from 'react-router-dom';

const useForgot = () => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const [pass, setPass] = useState('');
  const [confirmPass, setConfirmPass] = useState('');
  

  const navigate = useNavigate();

  const [showLoader, setShowLoader] = useState(false);
  const [modalMessage, setModalMessage] = useState('');
  const [modalType, setModalType] = useState('');

  const forgotPassword = async () => {
    setLoading(true);
    setError(null);
    const dataForgot = {
      EMAIL : user
    }
    try {
      await authService.forgotPassword(dataForgot);
      setLoading(false);
      setUser('');
      setModalType("SUCCESS");
      handleShowLoader("We've sent a link to your email to help you reset your password. Please check your inbox to continue.");
    } catch (err) {
      setLoading(false);
      setModalType("ERROR")
      handleShowLoader(err.message);
    }
  };

  const updatePassword = async (token) => {
    setLoading(true);
    setError(null);
    const dataReset = {
      TOKEN : token,
      NEW_PASSWORD: pass,
      CONFIRM_NEW_PASSWORD: confirmPass
    }
    try {
      await authService.resetPass(dataReset);
      setLoading(false);
      setUser('');
      setModalType("SUCCESS");
      handleShowLoader("Your password has been successfully reset. Please login with your new password.");
    } catch (err) {
      setLoading(false);
      setModalType("ERROR")
      handleShowLoader(err.message);
    }
  };

  const handleCloseLoader = () => setShowLoader(false);
  const handleShowLoader = (message) => {
      setShowLoader(true);
      setModalMessage(message);
  };

  return {
    user,
    setUser,
    forgotPassword, 
    loading, 
    error,
    showLoader,
    handleShowLoader,
    handleCloseLoader,
    modalMessage,
    modalType,

    pass,
    setPass,
    confirmPass,
    setConfirmPass,
    updatePassword
  };
};

export default useForgot;
