import React, { useEffect, useRef, useState } from 'react'; import { Link, useLocation, useNavigate } from 'react-router-dom'; import { FaSignOutAlt, FaUser, FaBuilding, FaChevronDown, FaCheck, FaBars } from "react-icons/fa"; import api from '../config/api'; import { IoSettings, IoSettingsOutline } from 'react-icons/io5'; import { useSelector } from 'react-redux'; import { RootState } from '../store/store'; import { GoBell } from 'react-icons/go'; import getInitialsUtils from '../utlity/getInitialUtils'; interface AccountNavProps { accountName?: string | null; transactionName?: string | null; showSideBar?: boolean; setShowSideBar?: (show: boolean) => void; isMobile?: boolean; } interface Account { id: number; isDefault: boolean; name: string; } interface UserData { id: number; name: string; firstName: string; lastName: string; email: string; language: string; account: Account; } interface AccountDataArray { userId: number, userEmail: string, name: string, accountId: number; accountName: string; role: string; status: string; } // Helper function to dispatch custom storage event const dispatchSessionStorageChange = (key: string, newValue: any) => { window.dispatchEvent(new CustomEvent('sessionStorageChange', { detail: { key, newValue } })); }; const CommonNav: React.FC = ({ showSideBar, setShowSideBar, isMobile = false }) => { const activeAccountId = JSON.parse(sessionStorage.getItem('activeAccountId') || 'null'); const userDetails = JSON.parse(sessionStorage.getItem('userDetails') || '{}'); const userDetailsAsync = useSelector((state: RootState) => state.user) const [open, setOpen] = useState(false); const [accountsOpen, setAccountsOpen] = useState(false); const [loadingAccounts, setLoadingAccounts] = useState(false); const [accounts, setAccounts] = useState([]); const [hasModalBeenClosed, setHasModalBeenClosed] = useState(false); const dropdownRef = useRef(null); // const [initial, setInitial] = useState(""); const [user, setUser] = useState({ id: 0, name: "", firstName: "", lastName: "", email: "", language: "", account: { id: 0, isDefault: false, name: "", }, }); const handleSettingsClick = () => { setOpen(false); navigate("/s/settings#profile-info"); } // useEffect(() => { // if (initial != "") return // console.log(userDetailsAsync, 'line 89') // let initialN = (userDetailsAsync.firstName && userDetailsAsync.firstName[0]) // initialN = initialN + "" + (userDetailsAsync.lastName && userDetailsAsync.lastName[0]) // setInitial(initialN) // }, [userDetailsAsync]) const getAccountDetails = async () => { try { let res = await api.get('/api/v1/user/accounts'); let items = res?.data; const cleanedData: AccountDataArray[] = items.map((item: any) => ({ userId: item.userId, userEmail: item.userEmail, name: item.name, accountId: item.accountId, accountName: item.accountName, role: item.role, status: item.status, })); setAccounts(cleanedData); } catch (error) { console.log(error); } }; const handleAccountsClick = async () => { setAccountsOpen(!accountsOpen); if (!accountsOpen) { setLoadingAccounts(true); if (accounts.length == 0 || hasModalBeenClosed) { await getAccountDetails(); setHasModalBeenClosed(false); } setLoadingAccounts(false); } }; const handleAccountSwitch = (account: any) => { // Update sessionStorage sessionStorage.setItem('activeAccountId', JSON.stringify(account.accountId)); // Dispatch custom event dispatchSessionStorageChange('activeAccountId', account.accountId); // Update user state setUser({ id: account.userId, name: account.name, firstName: account.firstName, lastName: account.lastName, email: account.userEmail, language: account.language, // set it if available account: { id: account.accountId, isDefault: false, // update as needed name: account.accountName, }, }); // if (account.firstName && account.lastName) { // setInitial((account?.firstName?.slice(0, 1)).toUpperCase() + "" + (account?.lastName?.slice(0, 1)).toUpperCase()) // } else { // setInitial((account?.name?.slice(0, 1)).toUpperCase()) // } sessionStorage.setItem('userDetails', JSON.stringify({ id: account.userId, name: account.name, email: account.userEmail, language: account.language, // set it if available account: { id: account.accountId, isDefault: false, // update as needed name: account.accountName, }, })); setAccountsOpen(false); setOpen(false); }; const navigate = useNavigate(); const getUserDetails = async () => { try { let res = await api.get(`/api/v1/user/details`); const item = res?.data; if (item) { const userData = { id: item?.id, name: item?.firstName + " " + item?.lastName, firstName: item?.firstName, lastName: item?.lastName, email: item?.email, language: item?.language, account: { id: item?.account.id, isDefault: false, name: item?.account.name, }, }; setUser(userData); // if (userData.firstName && userData.lastName) { // setInitial((userData?.firstName?.slice(0, 1)).toUpperCase() + "" + (userData?.lastName?.slice(0, 1)).toUpperCase()) // } else { // setInitial((userData?.name?.slice(0, 1)).toUpperCase()) // } sessionStorage.setItem('userDetails', JSON.stringify(userData)); sessionStorage.setItem('activeAccountId', JSON.stringify(userData.account.id)); // Dispatch event for initial load dispatchSessionStorageChange('activeAccountId', userData.account.id); } } catch (error) { console.error("Error fetching user details:", error); } }; useEffect(() => { if (!activeAccountId) { getUserDetails(); } else { setUser(userDetails); } }, []); const location = useLocation(); const rawPathnames = location.pathname .split("/") .filter((x) => x && isNaN(Number(x))); useEffect(() => { function handleClickOutside(event: MouseEvent) { if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { if (open) { setHasModalBeenClosed(true); } setOpen(false); setAccountsOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, [open]); const handleLogout = async () => { api.get(`${import.meta.env.VITE_BASE_URI}/api/v1/auth/logout`).then((res) => { sessionStorage.clear(); localStorage.clear(); // Redirect to login or refresh the page after logout // window.location.href = '/login'; }).catch((err) => { sessionStorage.clear(); localStorage.clear(); window.location.href = '/login'; }); }; const handleMainDropdownToggle = () => { if (open) { setHasModalBeenClosed(true); } setOpen(!open); if (!open) { setAccountsOpen(false); } }; const handleSidebarToggle = () => { if (setShowSideBar) { setShowSideBar(!showSideBar); } }; // Special case: if first segment is 's' and next is 'settings', remove 's' const pathnames = rawPathnames[0] == "s" && rawPathnames[1] == "settings" ? rawPathnames.slice(1) : rawPathnames; const labelMap: Record = { accounts: "Accounts", transactions: "Transactions", templates: "Templates", }; const formatSegment = (segment: string) => segment .replace(/[-_]/g, " ") .replace(/\b\w/g, (char) => char.toUpperCase()); // If URL has accounts → transactions, only keep "transactions" let filteredPathnames = [...pathnames]; const accIndex = pathnames.indexOf("accounts"); const txnIndex = pathnames.indexOf("transactions"); if (accIndex != -1 && txnIndex != -1 && txnIndex > accIndex) { // keep only "transactions" and everything after it filteredPathnames = pathnames.slice(txnIndex); } const ShimmerRow = () => (
); return ( <>
{/* Mobile Hamburger Menu - Only show on mobile */} {isMobile && (
SME
)} {/* Breadcrumb Navigation */}
{/* SETINGS - START */}
{/* SETINGS - END */} {/* Bell START */}
{/* Bell END */}
{open && (
{user ? ( {getInitialsUtils((user.firstName ?? '') + (user.firstName && user.lastName ? ' ' : '') + (user.lastName ?? ''))} ) : ( )}
{user?.name || '-'}
{user?.email || '-'}
Account #{user?.account?.name || '-'}
{accountsOpen && (
{loadingAccounts ? (
) : (
{accounts?.length > 0 ? ( accounts?.map((account) => ( )) ) : ( No Account... )}
)}
)}
)}
); } export default CommonNav;