import React, { useState } from "react"; import { Box, Button, TextField, Typography, InputAdornment, IconButton, Link as MuiLink, } from "@mui/material"; import { Visibility, VisibilityOff } from "@mui/icons-material"; import { useNavigate, Link } from "react-router-dom"; import toast from "react-hot-toast"; import axiosInstance, { setAccessToken } from "../../api/axiosInstance"; import PromoPanel from "../../components/auth/PromoPanel"; const LoginPage = () => { const navigate = useNavigate(); const [showPassword, setShowPassword] = useState(false); const [loading, setLoading] = useState(false); const [formData, setFormData] = useState({ mobile: "", password: "", }); const [errors, setErrors] = useState({}); const handleChange = (e) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: value, })); if (errors[name]) { setErrors((prev) => ({ ...prev, [name]: "" })); } }; const validate = () => { const newErrors = {}; if (!formData.mobile) newErrors.mobile = "Mobile number is required"; else if (!/^\d{10}$/.test(formData.mobile)) newErrors.mobile = "Enter a valid 10-digit mobile number"; if (!formData.password) newErrors.password = "Password is required"; setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleLogin = async (e) => { e.preventDefault(); if (!validate()) return; setLoading(true); // Retrieve FCM token from localStorage const fcmToken = localStorage.getItem("fcm_token") || ""; const payload = { mobile: formData.mobile, password: formData.password, web_fcm_token: fcmToken, }; try { const response = await axiosInstance.post("/login", payload); const data = response.data; // Extract token from response const token = data?.access_token || data?.token || data?.accessToken || data?.data?.access_token; if (token) { // Store token in localStorage and axios instance localStorage.setItem("access_token", token); setAccessToken(token); // Store profile_id and user_id for WebSocket channels const profileId = data?.profile_id || data?.data?.profile_id; const userId = data?.user_id || data?.data?.user_id; if (profileId) localStorage.setItem("profile_id", profileId); if (userId) localStorage.setItem("user_id", userId); toast.success("Login Successful!"); navigate("/dashboard-home"); } else { toast.error("Login failed: No access token received."); } } catch (error) { console.error("Login error:", error); const errorMessage = error?.response?.data?.message || error?.response?.data?.error || "Login failed. Please check your credentials."; toast.error(errorMessage); } finally { setLoading(false); } }; return (
Welcome Back Please login to your account
setShowPassword(!showPassword)} edge="end" > {showPassword ? : } ), }} /> Forgot Password? Don't have an account?{" "} Register Now
); }; export default LoginPage;