import { LoginPost, LogoutGet } from '@/services/auth-service'
import { useRouter } from 'next/router'
import { destroyCookie, parseCookies, setCookie } from 'nookies'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { UPDATE_NAME } from 'store/userSlice'
import Swal from 'sweetalert2'
import axios from '../lib/axios'

export const useAuth = ({ middleware, redirectIfAuthenticated }) => {
	const router = useRouter()
	const { token } = parseCookies()
	const dispatch = useDispatch()

	useEffect(() => {
		if (middleware === 'guest' && redirectIfAuthenticated && token) router.push(redirectIfAuthenticated)
		if (middleware === 'auth' && !token) logout()
	}, [token])

	const login = async ({ toast, setLoading, ...props }) => {
		LoginPost(props)
			.then((res) => {
				setLoading(false)
				if (res.status === 'ok') {
					setCookie(null, 'token', res.data.jwt, {
						path: '/',
						maxAge: res.data.token_expiry,
					})
					localStorage.setItem('menus', JSON.stringify(res.data.user_access))
					localStorage.setItem('user', JSON.stringify(res.data))
				} else {
					// eslint-disable-next-line no-undef
					grecaptcha.reset()
					toast.current.show({ severity: 'error', summary: 'Error Message', detail: res.message })
				}
			})
			.catch((err) => {
				// eslint-disable-next-line no-undef
				grecaptcha.reset()
				setLoading(false)
				switch (err.response.status) {
					case 401:
						toast.current.show({
							severity: 'error',
							summary: 'Error Message',
							detail: 'Your account used on another device.',
						})
						break

					default:
						toast.current.show({ severity: 'error', summary: 'Error Message', detail: err })
						break
				}
			})
	}

	const forgotPassword = async ({ ...props }) => {
		axios
			.post('/security/forgotPassword ', props)
			.then((response) => {
				Swal.fire({
					icon: 'success',
					title: 'Forgot Password',
					text: response.data.message,
					width: '25rem',
					timer: 3000,
					timerProgressBar: true,
				}).then(() => {
					router.push('/')
				})
			})
			.catch((err) => {
				console.log(err)
			})
	}

	const resetPassword = async ({ ...props }) => {
		axios
			.post('/security/resetPassword ', props)
			.then((response) => {
				Swal.fire({
					icon: 'success',
					title: 'Reset Password',
					text: response.data.message,
					width: '25rem',
					timer: 3000,
					timerProgressBar: true,
				}).then(() => {
					router.push('/')
				})
			})
			.catch((err) => {
				console.log(err)
			})
	}

	const logout = async () => {
		LogoutGet()
			.then((res) => {
				if (res.status === 'ok') {
					destroyCookie(null, 'token', { path: '/' })
					localStorage.removeItem('menus')
					localStorage.removeItem('user')
					dispatch(UPDATE_NAME(''))
					router.push('/')
				}
			})
			.catch((err) => console.log(err))
	}

	return {
		// user,
		login,
		logout,
		forgotPassword,
		resetPassword,
	}
}
