import { authService } from '@/services/api/auth.service'; import { initializeAuthenticatedApp } from '@/services/initializer.service'; import { useAppStore } from '@/store/app.store'; import { useAuthStore } from '@/store/auth.store'; import type { LoginPayload } from '@/types'; import { ROUTES } from '@/utils/routes'; import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; export const useLoginForm = () => { const router = useRouter(); const setAccessToken = useAuthStore((state) => state.setAccessToken); const setLoading = useAppStore((state) => state.setLoading); const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm({ defaultValues: { email: '', password: '', rememberMe: false, }, }); const onSubmit = async (data: LoginPayload) => { try { const loginResponse = await authService.login({ email: data.email, password: data.password, }); const accessToken = loginResponse.access_token; if (!accessToken) { toast.error('Login failed: no access token returned'); return; } setAccessToken(accessToken); setLoading(); await initializeAuthenticatedApp(); toast.success('Login successful'); router.replace(ROUTES.DASHBOARD); } catch (error) { toast.error(error instanceof Error ? error.message : 'Unable to sign in'); } }; return { register, handleSubmit: handleSubmit(onSubmit), errors, isLoading: isSubmitting, }; };