"use client"; import React, { useEffect, useState } from 'react'; import { Button, Input, Group, Stack, Text, Title, Box, Select, Paper, Switch } from '@mantine/core'; import { IconBuildingBank, IconEye, IconLink } from '@tabler/icons-react'; import { useRouter } from "next/navigation"; import { Providers } from "../../providers"; import { notifications } from '@mantine/notifications'; import dayjs from 'dayjs'; import { useMediaQuery } from '@mantine/hooks'; interface accountData { stAccountNo: string; stAccountType: string; stAvailableBalance: string; custname: string; activeAccounts: string; } export default function Home() { const [authorized, SetAuthorized] = useState(null); const router = useRouter(); const isMobile = useMediaQuery("(max-width: 768px)"); const [userName, setUserName] = useState(""); const [accountData, SetAccountData] = useState([]); const depositAccounts = accountData.filter(acc => acc.stAccountType !== "LN"); const [selectedDA, setSelectedDA] = useState(depositAccounts[0]?.stAccountNo || ""); const selectedDAData = depositAccounts.find(acc => acc.stAccountNo === selectedDA); const loanAccounts = accountData.filter(acc => acc.stAccountType === "LN"); const [selectedLN, setSelectedLN] = useState(loanAccounts[0]?.stAccountNo || ""); const selectedLNData = loanAccounts.find(acc => acc.stAccountNo === selectedLN); const [showBalance, setShowBalance] = useState(false); const PassExpiryRemains = (dayjs(localStorage.getItem("pswExpiryDate"))).diff(dayjs(), "day") const [loadingAccountNo, setLoadingAccountNo] = useState(null); // If back and forward button is clicked useEffect(() => { window.history.pushState(null, "", window.location.href); const handlePopState = () => { localStorage.removeItem("access_token"); sessionStorage.removeItem("access_token"); localStorage.removeItem("remitter_name"); localStorage.removeItem("pswExpiryDate"); localStorage.clear(); sessionStorage.clear(); router.push("/login"); }; const handleBeforeUnload = () => { // logout on tab close / refresh localStorage.removeItem("access_token"); sessionStorage.removeItem("access_token"); localStorage.clear(); sessionStorage.clear(); }; window.addEventListener("popstate", handlePopState); window.addEventListener("beforeunload", handleBeforeUnload); return () => { window.removeEventListener("popstate", handlePopState); window.addEventListener("beforeunload", handleBeforeUnload); }; }, []); async function handleFetchUserDetails() { try { const token = localStorage.getItem("access_token"); const response = await fetch('api/customer', { method: 'GET', headers: { 'Content-Type': 'application/json', "X-Login-Type": "IB", 'Authorization': `Bearer ${token}` }, }); const data = await response.json(); if (response.ok && Array.isArray(data)) { SetAccountData(data); sessionStorage.setItem("accountData", JSON.stringify(data)); if (data.length > 0) { const firstDeposit = data.find(acc => acc.stAccountType !== "LN"); const firstLoan = data.find(acc => acc.stAccountType === "LN"); if (firstDeposit) setSelectedDA(firstDeposit.stAccountNo); if (firstLoan) setSelectedLN(firstLoan.stAccountNo); } } else { throw new Error(); } } catch { notifications.show({ withBorder: true, color: "red", title: "Please try again later", message: "Unable to Fetch, Please try again later", autoClose: 5000, }); } } async function handleGetAccountStatement(accountNo: string) { if (loadingAccountNo) return; setLoadingAccountNo(accountNo); // simulate loading delay setTimeout(() => { router.push(`/accounts/account_statement?accNo=${accountNo}`); setLoadingAccountNo(null); }, 6000); } useEffect(() => { const token = localStorage.getItem("access_token"); if (!token) { SetAuthorized(false); router.push("/login"); } else { SetAuthorized(true); } }, []); useEffect(() => { if (authorized) { handleFetchUserDetails(); const fullName = localStorage.getItem("remitter_name") || "User"; // const first = fullName.split(" ")[0]; setUserName(fullName); } }, [authorized]); if (authorized) { return ( {/* ---------------------- WELCOME CARD ---------------------- */} Welcome, {userName} {/* -------------------- ACCOUNT OVERVIEW HEADER -------------------- */} Accounts Overview Your accounts at a glance {/* --------------------- SHOW BALANCE TOGGLE ---------------------- */} Show Balance setShowBalance(event.currentTarget.checked)} /> {/* ----------------------- DESKTOP VIEW ------------------------ */} {!isMobile && ( {/* ----------------------- DEPOSIT CARD ----------------------- */} Deposit Account ({ value: acc.stAccountNo, label: `${acc.stAccountType}- ${acc.stAccountNo}`, }))} value={selectedLN} // @ts-ignore onChange={setSelectedLN} size="xs" styles={{ input: { backgroundColor: "white", color: "black", marginLeft: 30, width: 140 } }} /> {selectedLNData?.stAccountNo} {showBalance ? `₹${Number(selectedLNData?.stAvailableBalance || 0).toLocaleString("en-IN")}` : "****"} {/* ----------------------- QUICK LINKS ----------------------- */} Quick Links )} {/* ----------------------- MOBILE VERSION STAYS SAME ----------------------- */} {isMobile && ( {/* Deposit Account Card */} Deposit Account {depositAccounts.length > 0 ? ( ({ value: acc.stAccountNo, label: `${acc.stAccountType}- ${acc.stAccountNo}`, }))} value={selectedLN} // @ts-ignore onChange={setSelectedLN} size="xs" styles={{ input: { backgroundColor: "white", color: "black", marginLeft: 5, width: "150px", }, }} /> ) : ( No loan account available )} {loanAccounts.length > 0 ? ( <> {Number(selectedLNData?.stAccountNo || 0)} {showBalance ? `₹${Number(selectedLNData?.stAvailableBalance || 0).toLocaleString("en-IN")}` : "****"} ) : ( <> Apply for a loan account to get started )} {/* Important Links Card */} Quick Links )} {/* -------------------- NOTES SECTION (BOTTOM) --------------------- */} ** Book Balance includes uncleared effect. ** Click "Show Balance" to display account balances. ** Your Password will expire in {PassExpiryRemains} days. ); } return null; }