import React, { useState, useEffect } from "react"; import { useNavigate, Link, useLocation } from "react-router-dom"; import { z } from "zod"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import Logo from "@/components/ui/logo"; import { toast } from "@/lib/custom-toast"; import { authService, userSessionService } from "@/lib/api"; import { useAuth } from "@/lib/auth-context"; import { Download, Smartphone } from "lucide-react"; import CheckInBlockerDialog from "@/components/CheckInBlockerDialog"; import { attendanceApi } from "@/services/attendanceApi"; // Form schema and validation const formSchema = z.object({ email: z.string().email({ message: "Please enter a valid email address", }), password: z.string().min(1, { message: "Password is required", }), }); const Login = () => { const navigate = useNavigate(); const location = useLocation(); const from = location.state?.from?.pathname || "/"; const [isLoading, setIsLoading] = useState(false); const [apiError, setApiError] = useState(null); const [showPassword, setShowPassword] = useState(false); const [showCheckInDialog, setShowCheckInDialog] = useState(false); const [checkInLoading, setCheckInLoading] = useState(false); const [pendingUserData, setPendingUserData] = useState(null); const { login } = useAuth(); // Redirect to dashboard if already logged in useEffect(() => { // Removing the auto-redirect so users can log in again if needed }, []); // Form setup with validation const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { email: "", password: "" }, }); const handleCheckIn = async () => { if (!pendingUserData) return; try { setCheckInLoading(true); await attendanceApi.checkIn(pendingUserData.employeeId); toast.success("Checked in successfully!"); setShowCheckInDialog(false); // Small delay to ensure backend has processed the check-in await new Promise(resolve => setTimeout(resolve, 500)); login(pendingUserData); } catch (error: any) { toast.error(error?.response?.data || error?.message || "Failed to check in"); console.error('Check-in error:', error); } finally { setCheckInLoading(false); } }; const onSubmit = async (values: z.infer) => { try { setIsLoading(true); setApiError(null); // Call the real API const response = await authService.login({ email: values.email, password: values.password }); // Handle successful login if (response && response.userId) { // Log token details for debugging console.log('Login successful - token received:', !!response.token); if (response.token) { console.log('Token starts with:', response.token.substring(0, 20) + '...'); } else { console.error('WARNING: No token in the login response!'); } // Show success message toast.success(`Welcome back, ${response.firstName}!`); // Check if user is a client - clients don't need to check in if (response.roleName?.toLowerCase() === "client") { login(response); return; } // Check if user has checked in today try { const todayAttendance = await attendanceApi.getToday(response.employeeId); if (!todayAttendance || !todayAttendance.inTime) { // User hasn't checked in - show blocker dialog setPendingUserData(response); setShowCheckInDialog(true); setIsLoading(false); } else { // User already checked in - proceed with login login(response); } } catch (error) { console.error('Error checking attendance:', error); // If there's an error checking attendance, proceed with login anyway login(response); } } else { // If no userId in response throw new Error('Invalid user credentials'); } } catch (error: any) { setIsLoading(false); // Set error message const errorMessage = error.message || "Login failed. Please check your credentials."; setApiError(errorMessage); toast.error(errorMessage); console.error("Login error:", error); } finally { setIsLoading(false); } }; return (

Welcome back

Log in to your account to continue

Sign in Enter your credentials below {apiError && (
{apiError}
)}
( Email )} /> ( Password )} />
Need an account?
{/* Mobile App Download Section */}

PM-Tool Mobile App

Manage your projects on the go with our Android app

{/* Check-In Blocker Dialog */}
); }; export default Login;