import { Button, Container, Paper, Text, TextInput, PasswordInput, Group, Stack, Title, Center, Box, ThemeIcon, } from "@mantine/core"; import { useEffect, useState } from "react"; import { useForm } from "@mantine/form"; import { notifications } from "@mantine/notifications"; import { IconAt, IconLock, IconLogin, IconBrandWhatsapp } from "@tabler/icons-react"; import apiFetch from "../lib/apiFetch"; import clientRoutes from "@/clientRoutes"; import { Navigate } from "react-router-dom"; export default function Login() { const [loading, setLoading] = useState(false); const [isAuthenticated, setIsAuthenticated] = useState(null); const form = useForm({ initialValues: { email: "", password: "", }, validate: { email: (value) => (/^\S+@\S+$/.test(value) ? null : "Invalid email"), password: (value) => (value.length < 1 ? "Password is required" : null), }, }); useEffect(() => { async function checkSession() { try { const res = await apiFetch.api.user.find.get(); setIsAuthenticated(res.status === 200); } catch { setIsAuthenticated(false); } } checkSession(); }, []); const handleSubmit = async (values: typeof form.values) => { setLoading(true); try { const response = await apiFetch.auth.login.post({ email: values.email, password: values.password, }); if (response.data?.token) { localStorage.setItem("token", response.data.token); notifications.show({ title: "Login Successful", message: "Welcome back!", color: "green", }); window.location.href = clientRoutes["/sq/dashboard"]; return; } if (response.error) { notifications.show({ title: "Login Failed", message: (response.error as any)?.value?.message || "Invalid credentials", color: "red", }); } } catch (error) { console.error(error); notifications.show({ title: "Error", message: "An unexpected error occurred", color: "red", }); } finally { setLoading(false); } }; if (isAuthenticated === null) return null; if (isAuthenticated) return ; return ( Welcome Back! Login to manage your WhatsApp integration
} {...form.getInputProps("email")} /> } {...form.getInputProps("password")} />
); }