import Link from '@/core/components/elements/Link/Link' import { setAuth } from '@/core/utils/auth' import { useRouter } from 'next/router' import { useRef, useState } from 'react' import loginApi from '../api/loginApi' const useLogin = () => { const router = useRouter() const [isLoading, setIsLoading] = useState(false) const [alert, setAlert] = useState(null) const [isValid, setIsValid] = useState(false) const emailRef = useRef(null) const passwordRef = useRef(null) const inputVal = () => ({ email: emailRef.current.value, password: passwordRef.current.value }) const handleChangeInput = () => { const { email, password } = inputVal() const isValidInput = email && password setIsValid(isValidInput) } const handleSubmit = async (e) => { e.preventDefault() setAlert(null) setIsLoading(true) const { email, password } = inputVal() const login = await loginApi({ email, password }) setIsLoading(false) if (login.isAuth) { setAuth(login.user) router.push(router.query?.next || '/') return } switch (login.reason) { case 'NOT_FOUND': setAlert({ children: 'Email atau password tidak cocok', type: 'info' }) break case 'NOT_ACTIVE': setAlert({ children: ( <> Email belum diaktivasi, aktivasi sekarang ), type: 'info' }) break } } return { handleChangeInput, handleSubmit, isLoading, isValid, alert, emailRef, passwordRef } } export default useLogin