"use client"; import { fetchData } from "@/lib/data-service"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import Image from "next/image"; import Link from "next/link"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { toast } from "sonner"; export default function LoginPage() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [isLoading, setIsLoading] = useState(false); const [isRedirecting, setIsRedirecting] = useState(false); const router = useRouter(); // Check if already logged in useEffect(() => { const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (authToken) { router.push("/dashboard"); } }, [router]); async function handleLogin(e: React.FormEvent) { e.preventDefault(); if (isLoading || isRedirecting) return; setIsLoading(true); try { const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }), credentials: "include", }); const data = await response.json(); if (response.ok && data.token) { setIsRedirecting(true); document.cookie = `Authorization=${data.token}; path=/; Secure; SameSite=Strict; max-age=604800`; localStorage.setItem("Authorization", data.token); toast.success("Login successful"); setTimeout(() => { try { router.push("/dashboard"); setTimeout(() => { window.location.href = "/dashboard"; }, 1000); } catch (navError) { console.error("Navigation error:", navError); window.location.href = "/dashboard"; } }, 300); } else { const errorMessage = data.error || "Invalid credentials"; toast.error("Login Failed", { description: errorMessage, }); } } catch (error) { toast.error("Connection Error", { description: "Unable to connect to the server. Please check your internet connection and try again.", }); console.error("Login error:", error); } finally { setIsLoading(false); } } if (isRedirecting) { return (

Logging in

Redirecting to dashboard...

); } return (

Welcome back

Please sign in to your account

setUsername(e.target.value)} className="mt-1" />
setPassword(e.target.value)} className="mt-1" />

Don't have an account?{" "} Sign up

); }