"use client"; import React, { useCallback, useEffect, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { isValidZAPhone } from "@/lib/phone"; import { useDismissingState } from "@/hooks/useDismissingState"; import { TwoFactorChallenge, TwoFactorMethod } from "@/lib/auth"; import { User, Lock, ShieldAlert, ShieldCheck, ShieldOff, Trash2, Clock, LogIn, KeyRound, RotateCcw } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { useCampuses } from "@/hooks/useCampuses"; import { apiV2, apiV2Data } from "@/lib/apiV2"; type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string }; const ACTIVITY_META: Record string; icon: typeof LogIn }> = { login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn }, password_changed: { label: () => "Password changed", icon: KeyRound }, password_reset: { label: () => "Password reset via email link", icon: RotateCcw }, two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck }, two_factor_disabled: { label: () => "Two-factor authentication turned off", icon: ShieldOff }, }; const TWO_FACTOR_METHOD_LABEL: Record = { email: "email", whatsapp: "WhatsApp" }; export default function UserProfilePage() { const { user, token, logout, updateToken } = useAuth(); const router = useRouter(); useEffect(() => { if (!user && !token) router.replace("/login"); }, [user, token, router]); // ── Profile form ───────────────────────────────────────────────────────── const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [phone, setPhone] = useState(""); const [notifPref, setNotifPref] = useState<"email" | "whatsapp" | "both">("email"); const [homeCampusId, setHomeCampusId] = useState(""); const campusInfo = useCampuses(); const [profileMsg, setProfileMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const [savingProfile, setSavingProfile] = useState(false); const hasValidPhone = isValidZAPhone(phone); useEffect(() => { if (user) { setName(user.name || ""); setEmail(user.email || ""); setPhone(user.phoneNumber || ""); setNotifPref(user.notificationPreference || "email"); setHomeCampusId(user.homeCampusId || ""); } }, [user]); const saveProfile = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setSavingProfile(true); setProfileMsg(null); try { const res = await apiV2("patch", "/me", { authToken: token, body: { name, email, phone: phone || null, notificationPreference: hasValidPhone ? notifPref : "email", ...(campusInfo.enabled ? { homeCampusId: homeCampusId || null } : {}), }, }); // A refreshed token comes back — save it so the session stays valid updateToken(res.token); setProfileMsg({ type: "ok", text: "Profile updated." }); } catch (e) { setProfileMsg({ type: "err", text: errorMessage(e) || "Failed to update profile." }); } finally { setSavingProfile(false); } }; // ── Password change ─────────────────────────────────────────────────────── const [currentPassword, setCurrentPassword] = useState(""); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [pwMsg, setPwMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const [savingPw, setSavingPw] = useState(false); const changePassword = async (e: React.FormEvent) => { e.preventDefault(); if (newPassword !== confirmPassword) { setPwMsg({ type: "err", text: "Passwords do not match." }); return; } if (newPassword.length < 8) { setPwMsg({ type: "err", text: "Password must be at least 8 characters." }); return; } if (!token) return; setSavingPw(true); setPwMsg(null); try { const res = await apiV2("patch", "/me", { authToken: token, body: { currentPassword, password: newPassword } }); updateToken(res.token); setCurrentPassword(""); setNewPassword(""); setConfirmPassword(""); setPwMsg({ type: "ok", text: "Password changed." }); loadActivity(); } catch (e) { setPwMsg({ type: "err", text: errorMessage(e) || "Failed to change password." }); } finally { setSavingPw(false); } }; // ── Revoke sessions ─────────────────────────────────────────────────────── const [revokeMsg, setRevokeMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const [revoking, setRevoking] = useState(false); const revokeSessions = async () => { if (!confirm("This will sign you out of all other devices. You will need to log in again everywhere except here. Continue?")) return; if (!token) return; setRevoking(true); setRevokeMsg(null); try { const res = await (apiV2Data("post", "/me/sessions/revoke", { authToken: token, body: {}, }) as Promise<{ token?: string; message?: string }>); // Revoking sessions invalidates the token this device was using too — // save the freshly issued one so this device stays signed in. if (res?.token) updateToken(res.token); setRevokeMsg({ type: "ok", text: res?.message || "All other sessions signed out." }); } catch (e) { setRevokeMsg({ type: "err", text: errorMessage(e) || "Failed to revoke sessions." }); } finally { setRevoking(false); } }; // ── Account activity ────────────────────────────────────────────────────── const [activity, setActivity] = useState([]); const [loadingActivity, setLoadingActivity] = useState(false); const loadActivity = useCallback(async () => { if (!token) return; setLoadingActivity(true); try { const res = await (apiV2Data("get", "/me/activity", { authToken: token }) as Promise); setActivity(Array.isArray(res) ? res : []); } catch { // Non-critical — just leave the list empty rather than showing an error banner. } finally { setLoadingActivity(false); } }, [token]); useEffect(() => { loadActivity(); }, [loadActivity]); // ── Two-factor authentication ───────────────────────────────────────────── // Mirrors the saved account state locally: the auth context's `user` is only // loaded once per page load, so it wouldn't reflect a change made here. const [tfEnabled, setTfEnabled] = useState(false); const [tfMethod, setTfMethod] = useState("email"); const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change">("idle"); const [tfPassword, setTfPassword] = useState(""); const [tfCode, setTfCode] = useState(""); const [tfChallenge, setTfChallenge] = useState(null); const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const [tfBusy, setTfBusy] = useState(false); // WhatsApp codes need the number that's actually saved, not one still being typed. const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || ""); // Admins and supervisors must keep 2FA on; they can only change the channel. const tfRequired = !!user?.twoFactorRequired; useEffect(() => { if (user) { setTfEnabled(!!user.twoFactorEnabled); setTfMethod(user.twoFactorMethod || "email"); } }, [user]); const resetTwoFactorForm = () => { setTfStep("idle"); setTfPassword(""); setTfCode(""); setTfChallenge(null); }; const startEnableTwoFactor = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setTfBusy(true); setTfMsg(null); try { const res = await (apiV2Data("post", "/me/two-factor/enable", { authToken: token, body: { method: tfMethod, password: tfPassword }, }) as Promise); setTfChallenge(res); setTfCode(""); setTfPassword(""); setTfStep("code"); } catch (e) { setTfMsg({ type: "err", text: errorMessage(e) || "Failed to send a verification code." }); } finally { setTfBusy(false); } }; const confirmEnableTwoFactor = async (e: React.FormEvent) => { e.preventDefault(); if (!token || !tfChallenge) return; setTfBusy(true); setTfMsg(null); try { const res = await (apiV2Data("post", "/me/two-factor/confirm", { authToken: token, body: { challengeId: tfChallenge.challengeId, code: tfCode }, }) as Promise<{ twoFactorMethod: TwoFactorMethod }>); const wasEnabled = tfEnabled; setTfEnabled(true); setTfMethod(res.twoFactorMethod); resetTwoFactorForm(); setTfMsg({ type: "ok", text: wasEnabled ? `Codes will now be sent by ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." }); loadActivity(); } catch (e) { setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." }); } finally { setTfBusy(false); } }; const disableTwoFactor = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setTfBusy(true); setTfMsg(null); try { await apiV2Data("post", "/me/two-factor/disable", { authToken: token, body: { password: tfPassword }, }); setTfEnabled(false); resetTwoFactorForm(); setTfMsg({ type: "ok", text: "Two-factor authentication is off." }); loadActivity(); } catch (e) { setTfMsg({ type: "err", text: errorMessage(e) || "Failed to turn off two-factor authentication." }); } finally { setTfBusy(false); } }; // ── Account closure ─────────────────────────────────────────────────────── const [closeStep, setCloseStep] = useState<"idle" | "confirm">("idle"); const [deleteData, setDeleteData] = useState(false); const [closePassword, setClosePassword] = useState(""); const [closeMsg, setCloseMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const [closing, setClosing] = useState(false); const submitAccountClosure = async (e: React.FormEvent) => { e.preventDefault(); if (!token) return; setClosing(true); setCloseMsg(null); try { const res = await (apiV2Data("post", "/me/close", { authToken: token, body: { password: closePassword, deleteData }, }) as Promise<{ message?: string }>); setCloseMsg({ type: "ok", text: res?.message || "Account closed." }); // Slight delay so the user can read the message, then log out setTimeout(() => logout(), 2500); } catch (e) { setCloseMsg({ type: "err", text: errorMessage(e) || "Failed to close account." }); } finally { setClosing(false); } }; // ── Shared helpers ──────────────────────────────────────────────────────── const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
{msg.text}
); const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof User; title: string; tone?: "brand" | "amber" | "red" }) => { const toneCls = tone === "amber" ? "bg-amber-50 text-amber-600" : tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600"; return (

{title}

); }; return (

Profile & Security

Manage your personal information and keep your account secure.

{/* ── Profile info ─────────────────────────────────────────────── */}
setName(e.target.value)} required />
setEmail(e.target.value)} required />
setPhone(e.target.value)} placeholder="e.g. 082 123 4567" />
{campusInfo.enabled && campusInfo.campuses.length > 0 && (

The events page starts on this campus, and you'll get messages meant for people at this campus.

)} {hasValidPhone && (

Security alerts (password reset, login notifications) are always sent via email regardless of this setting.

)} {profileMsg && }
{/* ── Account activity ─────────────────────────────────────────── */}
{loadingActivity && activity.length === 0 ? (

Loading…

) : activity.length === 0 ? (

No recent activity recorded yet.

) : (
    {activity.map(ev => { const meta = ACTIVITY_META[ev.type] || ACTIVITY_META.login; const Icon = meta.icon; return (
  • {meta.label(ev.device)}
    {new Date(ev.createdAt).toLocaleString()}
  • ); })}
)}
{/* ── Password ─────────────────────────────────────────────────── */}
setCurrentPassword(e.target.value)} required autoComplete="current-password" />
setNewPassword(e.target.value)} required minLength={8} autoComplete="new-password" />
setConfirmPassword(e.target.value)} required autoComplete="new-password" />
{pwMsg && }
{/* ── Two-factor authentication ────────────────────────────────── */}
{tfStep === "code" && tfChallenge ? (

We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}

setTfCode(e.target.value.replace(/\D/g, ""))} required />
) : tfEnabled && tfStep !== "change" ? ( <>

On. When you log in we send a 6-digit code by{" "} {TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you've chosen to trust skip the code for 30 days.

{tfRequired ? ( <>

Required for your role, so it can't be turned off.

) : tfStep !== "disable" ? ( ) : (
setTfPassword(e.target.value)} required autoComplete="current-password" />
)} ) : (

{tfEnabled ? "Choose where your login codes go. We'll send a code there first to check it reaches you." : "Add a second step to logging in: after your password, we send a 6-digit code that you need to enter."}

{!canWhatsAppCodes && (

Save a valid phone number on your profile to receive codes by WhatsApp.

)}
setTfPassword(e.target.value)} required autoComplete="current-password" />
{tfEnabled && ( )}
)} {tfMsg && }
{/* ── Security ─────────────────────────────────────────────────── */}

If you suspect someone else has access to your account, you can sign out of all other devices immediately. You will remain logged in on this device.

{revokeMsg && }
{/* ── Danger zone ──────────────────────────────────────────────── */}

Closing your account will deactivate it immediately. You can also ask for your personal information to be deleted — we do that once the request is processed (see{" "} Privacy). Tickets and payment records remain for accounting purposes but show as "Deleted User".

{closeStep === "idle" && ( )} {closeStep === "confirm" && (
This action cannot be undone. Please read carefully before continuing.
setClosePassword(e.target.value)} required placeholder="Enter your password to confirm" autoComplete="current-password" />
{closeMsg && } )}
); }