import { useMutation } from '@tanstack/react-query';
// import { submitLogin } from 'app/auth/store/loginSlice';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router';
// import { useLocation, useHistory } from 'react-router-dom';
import { submitLogin } from 'src/auth/store/loginSlice';
// import { endpoints } from 'src/lib/axios';
import type { AppDispatch } from 'src/store.tsx';

// const getUserInfo = async (token: any) => {
//   axios.defaults.headers.common.Authorization = `Bearer ${window.atob(token)}`;
//   const res = await axios.post(endpoints.auth.me);
//   const { data } = await res.data;

//   return data.user;
// };

interface SignInParams {
  email: string;
  password: string;
}

const useLogin = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();

  const mutation = useMutation({
    mutationKey: ['login'],

    mutationFn: async (params: SignInParams) => {
      const { payload: loginActionPayload } = await dispatch(submitLogin(params));
      return loginActionPayload;
    },
    onSuccess: (data) => {
      console.log('Login Berhasil', data);
      navigate('/dashboard');
      navigate(0);
      //   window.location.href = "/dashboard";
    },
    onError: (error: any) => {
      console.error('Login failed', error);
    },
  });
  return mutation;
};

export default useLogin;
