"use client"; import React, { useEffect, useState, useRef } from "react"; import { Text, Title, Box, Image, Button, Group, Container, ActionIcon, Divider, PinInput, Paper, Stack, Center, Loader, } from "@mantine/core"; import { Providers } from "@/app/providers"; import { useRouter } from "next/navigation"; import NextImage from "next/image"; import logo from "@/app/image/logo1.jpg"; import { IconLogout, IconShieldCheck, IconRefresh } from "@tabler/icons-react"; import { useMediaQuery } from "@mantine/hooks"; import { sendOtp, verifyOtp } from "../otpUtils"; import { fetchUserDetails } from "../authUtils"; export default function VerifyOtpPage() { const router = useRouter(); const [authorized, setAuthorized] = useState(null); const [custname, setCustname] = useState(null); const [otp, setOtp] = useState(""); const [isVerifying, setIsVerifying] = useState(false); const [isResending, setIsResending] = useState(false); const [timer, setTimer] = useState(60); const [canResend, setCanResend] = useState(false); const isMobile = useMediaQuery("(max-width: 768px)"); const timerRef = useRef(null); const otpSentRef = useRef(false); //On First Load: Check Token → Fetch User → Send OTP useEffect(() => { const token = localStorage.getItem("mandate_token"); if (!token) { handleLogout(); setAuthorized(false); return; } setAuthorized(true); // Get User Name + Mobile fetchUserDetails().then((res) => { if (res) { setCustname(res.name); if (!otpSentRef.current) { sendOtp(res.mobile); // sendOtp("7890544527"); otpSentRef.current = true; // Prevent second OTP } } }); // Prevent back button const handlePopState = () => { handleLogout(); }; window.addEventListener("popstate", handlePopState); window.history.pushState(null, "", window.location.href); return () => { window.removeEventListener("popstate", handlePopState); if (timerRef.current) clearInterval(timerRef.current); }; }, []); // Timer Countdown useEffect(() => { timerRef.current = setInterval(() => { setTimer((prev) => { if (prev === 1) { setCanResend(true); clearInterval(timerRef.current!); } return prev - 1; }); }, 1000); return () => clearInterval(timerRef.current!); }, []); // Logout const handleLogout = () => { localStorage.clear(); router.push("/eMandate/logout"); }; //Resend OTP const handleResendOtp = async () => { setIsResending(true); const mobile = localStorage.getItem("userMobNo"); // const mobile = "7890544527"; if (!mobile) return; await sendOtp(mobile); setTimer(60); setCanResend(false); setOtp(""); setIsResending(false); }; // Verify OTP using verifyOtp() Utility // const handleVerifyOtp = async () => { // const mobile = localStorage.getItem("userMobNo"); // // const mobile = "7890544527"; // if (!mobile || otp.length !== 6) return; // setIsVerifying(true); // const success = await verifyOtp(otp, mobile); // // if (success) { // // // const encoded_data = localStorage.getItem("Validate_data"); // // // const res = await fetch( // // // `https://apiemandate.kccb.in:9035/EMandate/auth-cbs-resp?data=${encoded_data}`, // // // { // // // method: "POST", // // // headers: { // // // "Content-Type": "application/json", // // // }, // // // } // // // ); // // const formData = new FormData(); // // const encoded_data = localStorage.getItem("Validate_data"); // // formData.append("data", encoded_data); // // const res = await fetch( // // "https://apiemandate.kccb.in:9035/EMandate/auth-cbs-resp", // // { // // method: "POST", // // body: formData, // // } // // ); // // const result = await res.json(); // // console.log(result); // // if (!res.ok) { // // throw new Error("CBS response API failed"); // // } // // if (res.ok) { // // // navigate only after successful API hit // // setTimeout(() => { // // router.push("/eMandate/mandate_page"); // // }, 1500); // // } // // } // if (success) { // try { // const encoded_data = localStorage.getItem("Validate_data"); // if (!encoded_data) { // console.error("Validate_data not found in localStorage"); // return; // } // const formData = new FormData(); // formData.append("data", encoded_data); // const res = await fetch( // "https://apiemandate.kccb.in:9035/EMandate/auth-cbs-resp", // { // method: "POST", // body: formData, // } // ); // if (!res.ok) { // throw new Error(`CBS response API failed: ${res.status}`); // } // const contentType = res.headers.get("content-type"); // const result = // contentType && contentType.includes("application/json") // ? await res.json() // : await res.text(); // console.log("CBS Response:", result); // setTimeout(() => { // router.push("/eMandate/mandate_page"); // }, 1000); // } catch (error) { // console.error("CBS API Error:", error); // } // } // else { // setOtp(""); // } // setIsVerifying(false); // }; const handleVerifyOtp = async () => { const mobile = localStorage.getItem("userMobNo"); if (!mobile || otp.length !== 6) return; setIsVerifying(true); const success = await verifyOtp(otp, mobile); if (success) { const encoded_data = localStorage.getItem("Validate_data"); if (!encoded_data) { console.error("Validate_data not found in localStorage"); setIsVerifying(false); return; } const url = "https://apiemandate.kccb.in:9035/EMandate/auth-cbs-resp"; console.log("Redirecting (POST) to URL:", url); console.log("POST Body Data:", { data: encoded_data }); // Create a form for POST redirect const form = document.createElement("form"); form.method = "POST"; form.action = url; // Add hidden field "data" const input = document.createElement("input"); input.type = "hidden"; input.name = "data"; input.value = encoded_data; form.appendChild(input); document.body.appendChild(form); // Submit → browser navigates to URL using POST form.submit(); return; } else { setOtp(""); } setIsVerifying(false); }; if (authorized === null) { return (
); } return ( {/* HEADER */} KCC Bank Logo {!isMobile && ( THE KANGRA CENTRAL CO-OPERATIVE BANK LTD. )} {isMobile ? ( ) : ( )} {/* WELCOME BAR */} Welcome, {custname ?? "User"} {/* MAIN CONTENT */}
{/* Icon */} {/* Title */} OTP Verification Enter the 6-digit OTP sent to your registered mobile number {localStorage.getItem("userMobNo")?.replace( /(\d{2})(\d{4})(\d{4})/, "+91 $1****$3" )} {/* OTP Input */} {/* Timer */} {canResend ? ( "Didn't receive OTP?" ) : ( <> Resend OTP in{" "} {timer}s )} {/* Verify Button */} {/* Resend Button */} {/* Info */} Note:{" "} Please do not share your OTP with anyone. KCC Bank will never ask for your OTP.
{/* FOOTER */} © 2025 The Kangra Central Co-Operative Bank Ltd. All rights reserved.
); }