Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | 1x 1x 54x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 287x 216x 287x 179x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 287x 5x 5x 5x 1x 4x 4x 4x 3x 3x 3x 3x 1x 4x 287x 8x 8x 1x 1x 7x 7x 7x 6x 6x 1x 1x 287x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 287x 1x 1x 1x 287x 9x 9x 1x 1x 8x 8x 8x 7x 7x 1x 1x 287x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 287x 1x 1x 1x 287x 4x 4x 3x 2x 3x 3x 3x 1x 1x 287x 4x 4x 4x 3x 3x 3x 3x 1x 4x 287x 5x 1x 7x 7x 1x 6x 2x 10x 10x 1x 1x 12x 12x 1x 1x 1x 1x | import { useState, useEffect, useRef, lazy, Suspense, type FormEvent } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { DrawerDialog } from "../components/ui/drawer-dialog";
import { useAuth } from "../lib/auth-context";
import { authApi, getErrorMessage } from "../lib/api";
import { getImageUrl } from "../lib/api/base";
import { notify } from "../lib/notify";
import { useCropFlow } from "../hooks/useCropFlow";
import { useUserProfile, useLinkedAccounts } from "../hooks/queries/useSettingsQueries";
import { ChangePasswordDialog } from "../components/settings/change-password-dialog";
import { ThemeSwitcher } from "../components/ui/theme-switcher";
import { queryKeys } from "../lib/query-keys";
import { Save, Upload, Lock, Settings } from "lucide-react";
import { StickyPageHeader } from "../components/ui/sticky-page-header";
import { PushPermissionBanner } from "../components/pwa/PushPermissionBanner";
import { IosBanner } from "../components/pwa/IosBanner";
import { EmailChangeSection } from "./EmailChangeSection.subcomponent";
import { PhoneChangeSection } from "./PhoneChangeSection.subcomponent";
const ImageCropper = lazy(() =>
import("../components/blogs/ImageCropper").then((m) => ({ default: m.ImageCropper })),
);
function isPhonePlaceholderEmail(email: string): boolean {
return email.endsWith("@phone.interioring.com");
}
export function SettingsPage() {
const { user, refreshSession } = useAuth();
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
// Load profile data via React Query
const { data: profile } = useUserProfile();
// Profile form state
const [name, setName] = useState("");
const [originalName, setOriginalName] = useState("");
const [nameTouched, setNameTouched] = useState(false);
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
const [formInitialized, setFormInitialized] = useState(false);
const [isSavingProfile, setIsSavingProfile] = useState(false);
const [isRemovingAvatar, setIsRemovingAvatar] = useState(false);
const nameError = nameTouched && !name.trim() ? "Name is required" : undefined;
const hasProfileChanges = name.trim() !== originalName.trim();
// Email change state
const [email, setEmail] = useState("");
const [originalEmail, setOriginalEmail] = useState("");
const [isPlaceholderEmail, setIsPlaceholderEmail] = useState(false);
const [emailOtpStep, setEmailOtpStep] = useState<"idle" | "sending" | "otp-sent" | "verifying">(
"idle",
);
const [emailOtp, setEmailOtp] = useState("");
// Phone change state
const [phoneNumber, setPhoneNumber] = useState("");
const [originalPhone, setOriginalPhone] = useState("");
const [phoneOtpStep, setPhoneOtpStep] = useState<"idle" | "sending" | "otp-sent" | "verifying">(
"idle",
);
const [phoneOtp, setPhoneOtp] = useState("");
// Change password dialog state
const [isPasswordDialogOpen, setIsPasswordDialogOpen] = useState(false);
// Determine if user has a password via React Query
const { data: linkedAccounts } = useLinkedAccounts();
const hasPassword = linkedAccounts
? linkedAccounts.some((a) => a.providerId === "credential")
: true; // Default to true (show "Change Password") while loading or on error
// Initialize form state from query data
useEffect(() => {
if (profile && !formInitialized) {
setName(profile.name || "");
setOriginalName(profile.name || "");
setAvatarUrl(profile.image || null);
const profileEmail = profile.email || "";
const placeholder = isPhonePlaceholderEmail(profileEmail);
setIsPlaceholderEmail(placeholder);
setEmail(placeholder ? "" : profileEmail);
setOriginalEmail(placeholder ? "" : profileEmail);
const rawPhone = (profile.phoneNumber || "").replace(/^\+91/, "");
setPhoneNumber(rawPhone);
setOriginalPhone(rawPhone);
setFormInitialized(true);
}
}, [profile, formInitialized]);
const handleSaveProfile = async (e: FormEvent) => {
e.preventDefault();
setNameTouched(true);
if (!name.trim()) {
return;
}
setIsSavingProfile(true);
try {
await authApi.updateProfile({ name: name.trim() });
setOriginalName(name.trim());
await refreshSession();
queryClient.invalidateQueries({ queryKey: queryKeys.settings.profile() });
notify.success("Profile updated successfully");
} catch (err) {
notify.error(getErrorMessage(err));
} finally {
setIsSavingProfile(false);
}
};
const handleSendEmailOtp = async () => {
const newEmail = email.trim();
if (!newEmail) {
notify.error("Please enter an email address");
return;
}
setEmailOtpStep("sending");
try {
await authApi.sendEmailChangeOtp(newEmail);
setEmailOtpStep("otp-sent");
notify.success("Verification code sent to your new email");
} catch (err) {
notify.error(getErrorMessage(err));
setEmailOtpStep("idle");
}
};
const handleVerifyEmailOtp = async () => {
if (!emailOtp.trim() || emailOtp.length !== 6) {
notify.error("Please enter the 6-digit code");
return;
}
setEmailOtpStep("verifying");
try {
await authApi.verifyEmailChange(email.trim(), emailOtp.trim());
setOriginalEmail(email.trim());
setIsPlaceholderEmail(false);
setEmailOtpStep("idle");
setEmailOtp("");
await refreshSession();
queryClient.invalidateQueries({ queryKey: queryKeys.settings.profile() });
notify.success("Email updated successfully");
} catch (err) {
notify.error(getErrorMessage(err));
setEmailOtpStep("otp-sent");
}
};
const handleCancelEmailChange = () => {
setEmail(originalEmail);
setEmailOtpStep("idle");
setEmailOtp("");
};
const handleSendPhoneOtp = async () => {
const phone = phoneNumber.trim();
if (!phone || phone.length !== 10) {
notify.error("Please enter a valid 10-digit phone number");
return;
}
setPhoneOtpStep("sending");
try {
await authApi.sendPhoneChangeOtp(phone);
setPhoneOtpStep("otp-sent");
notify.success("OTP sent via WhatsApp");
} catch (err) {
notify.error(getErrorMessage(err));
setPhoneOtpStep("idle");
}
};
const handleVerifyPhoneOtp = async () => {
if (!phoneOtp.trim() || phoneOtp.length !== 6) {
notify.error("Please enter the 6-digit OTP");
return;
}
setPhoneOtpStep("verifying");
try {
await authApi.verifyPhoneChange(phoneNumber.trim(), phoneOtp.trim());
setOriginalPhone(phoneNumber.trim());
setPhoneOtpStep("idle");
setPhoneOtp("");
await refreshSession();
queryClient.invalidateQueries({ queryKey: queryKeys.settings.profile() });
notify.success("Phone number updated successfully");
} catch (err) {
notify.error(getErrorMessage(err));
setPhoneOtpStep("otp-sent");
}
};
const handleCancelPhoneChange = () => {
setPhoneNumber(originalPhone);
setPhoneOtpStep("idle");
setPhoneOtp("");
};
const avatarCropFlow = useCropFlow({
aspectRatio: 1,
outputName: "avatar.jpg",
onUpload: async (file) => {
try {
const response = await authApi.uploadAvatar(file);
if (response.data) {
setAvatarUrl(response.data.path);
}
await refreshSession();
queryClient.invalidateQueries({ queryKey: queryKeys.settings.profile() });
notify.success("Profile picture updated");
} catch (err) {
notify.error(getErrorMessage(err));
throw err;
}
},
});
const handleRemoveAvatar = async () => {
setIsRemovingAvatar(true);
try {
await authApi.removeAvatar();
setAvatarUrl(null);
await refreshSession();
queryClient.invalidateQueries({ queryKey: queryKeys.settings.profile() });
notify.success("Profile picture removed");
} catch (err) {
notify.error(getErrorMessage(err));
} finally {
setIsRemovingAvatar(false);
}
};
return (
<div className="space-y-6">
<StickyPageHeader>
<div className="w-full">
{/* Title row */}
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2">
<Settings className="h-6 w-6" />
Account Settings
</h1>
<ThemeSwitcher variant="icon" />
<div className="flex-1" />
{/* Desktop-only buttons */}
<div className="hidden sm:flex items-center gap-3">
<Button
variant="outline"
size="sm"
onClick={() => setIsPasswordDialogOpen(true)}
>
<Lock className="h-4 w-4" />
{hasPassword === false ? "Set Password" : "Change Password"}
</Button>
<Button
type="submit"
form="settings-profile-form"
size="sm"
isLoading={isSavingProfile}
disabled={!hasProfileChanges}
>
<Save className="h-4 w-4" />
Save Changes
</Button>
</div>
</div>
{/* Mobile-only buttons */}
<div className="flex gap-3 mt-3 sm:hidden">
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => setIsPasswordDialogOpen(true)}
>
<Lock className="h-4 w-4" />
{hasPassword === false ? "Set Password" : "Change Password"}
</Button>
<Button
type="submit"
form="settings-profile-form"
size="sm"
className="flex-1"
isLoading={isSavingProfile}
disabled={!hasProfileChanges}
>
<Save className="h-4 w-4" />
Save Changes
</Button>
</div>
</div>
</StickyPageHeader>
{/* Notification banners — also shown on Settings */}
<PushPermissionBanner />
<IosBanner />
{/* Personal Information */}
<form id="settings-profile-form" onSubmit={handleSaveProfile} className="space-y-6 max-w-2xl" noValidate>
{/* Avatar */}
<div className="flex items-center gap-6">
<div className="relative h-20 w-20 flex-shrink-0">
{avatarUrl ? (
<img
src={getImageUrl(avatarUrl)}
alt="Profile"
className="h-20 w-20 rounded-full object-cover border-2 border-border-default"
loading="lazy"
/>
) : (
<div className="h-20 w-20 rounded-full bg-primary-100 flex items-center justify-center border-2 border-border-default">
<span className="text-2xl font-semibold text-primary-700">
{user?.name?.charAt(0).toUpperCase() || "U"}
</span>
</div>
)}
</div>
<div className="flex flex-col gap-2">
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/avif"
className="hidden"
data-testid="avatar-file-input"
onChange={(e) => {
avatarCropFlow.handleFilePick(e.target.files?.[0]);
e.target.value = "";
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-4 w-4" />
Upload Photo
</Button>
{avatarUrl && (
<button
type="button"
onClick={handleRemoveAvatar}
disabled={isRemovingAvatar}
className="text-sm text-foreground-muted hover:text-red-600 transition-colors text-left"
>
{isRemovingAvatar ? "Removing..." : "Remove photo"}
</button>
)}
</div>
</div>
<DrawerDialog
open={avatarCropFlow.isCropping}
onClose={avatarCropFlow.cancelCropping}
title="Crop Profile Photo"
>
{avatarCropFlow.isUploading ? (
<div className="text-center py-12" data-testid="avatar-uploading">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mx-auto" />
<p className="mt-2 text-sm text-foreground-muted">
Uploading profile photo...
</p>
</div>
) : avatarCropFlow.cropperProps ? (
<Suspense
fallback={
<div className="text-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500 mx-auto" />
<p className="mt-2 text-sm text-foreground-muted">
Loading cropper...
</p>
</div>
}
>
<ImageCropper {...avatarCropFlow.cropperProps} />
</Suspense>
) : null}
</DrawerDialog>
{/* Name */}
<div className="space-y-2">
<label
htmlFor="settings-name"
className="text-sm font-medium text-foreground-default"
>
Name *
</label>
<Input
id="settings-name"
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={() => setNameTouched(true)}
error={nameError}
placeholder="Your full name"
maxLength={100}
/>
</div>
</form>
{/* Email */}
<EmailChangeSection
email={email}
originalEmail={originalEmail}
isPlaceholderEmail={isPlaceholderEmail}
emailOtpStep={emailOtpStep}
emailOtp={emailOtp}
onEmailChange={(value) => {
setEmail(value);
if (emailOtpStep === "otp-sent") {
setEmailOtpStep("idle");
setEmailOtp("");
}
}}
onOtpChange={setEmailOtp}
onSendOtp={handleSendEmailOtp}
onVerifyOtp={handleVerifyEmailOtp}
onCancel={handleCancelEmailChange}
/>
{/* Phone Number */}
<PhoneChangeSection
phoneNumber={phoneNumber}
originalPhone={originalPhone}
phoneOtpStep={phoneOtpStep}
phoneOtp={phoneOtp}
onPhoneChange={(value) => {
setPhoneNumber(value);
if (phoneOtpStep !== "idle") {
setPhoneOtpStep("idle");
setPhoneOtp("");
}
}}
onOtpChange={setPhoneOtp}
onSendOtp={handleSendPhoneOtp}
onVerifyOtp={handleVerifyPhoneOtp}
onCancel={handleCancelPhoneChange}
/>
<ChangePasswordDialog
open={isPasswordDialogOpen}
onClose={() => setIsPasswordDialogOpen(false)}
hasPassword={hasPassword ?? true}
onPasswordSet={() => queryClient.invalidateQueries({ queryKey: queryKeys.settings.accounts() })}
/>
</div>
);
}
|