Files
frontend/app/(main)/login/otp/page.tsx
T
TaNguyenThanhQuy c2afb3d3b5
Release package / release (push) Successful in 7m28s
fix: connect services to backend (#37)
Co-authored-by: Thanh Quy - wolf <524H0124@student.tdtu.edu.vn>
Reviewed-on: #37
Co-authored-by: TaNguyenThanhQuy <tanguyenthanhquy@noreply.localhost>
Co-committed-by: TaNguyenThanhQuy <tanguyenthanhquy@noreply.localhost>
2026-05-05 14:42:13 +00:00

174 lines
5.9 KiB
TypeScript

"use client";
import Button from "@/components/atoms/buttons/Button";
import ErrorMessageLogin from "@/components/atoms/errors/ErrorMessageLogin";
import { useAuth } from "@/lib/auth-context";
import { SHOP_INFO } from "@/lib/constants";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { FormEvent, useEffect, useState } from "react";
export default function LoginOtpPage() {
const router = useRouter();
const { setUser } = useAuth();
const [phone, setPhone] = useState("");
const [role, setRole] = useState("");
const [otp, setOtp] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [errors, setErrors] = useState({ otp: "", general: "" });
useEffect(() => {
const storedPhone = sessionStorage.getItem("login_phone");
const storedRole = sessionStorage.getItem("login_role");
if (!storedPhone || !storedRole) {
router.replace("/login");
return;
}
setPhone(storedPhone);
setRole(storedRole);
}, [router]);
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!otp.trim()) {
setErrors({ otp: "Please enter your OTP code", general: "" });
return;
}
setIsLoading(true);
setErrors({ otp: "", general: "" });
try {
const endpoint =
role === "manager"
? "/api/manager/quick_login"
: "/api/customer/quick_login";
const res = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone, otp }),
});
if (res.ok) {
const userData = await res.json();
setUser(userData);
localStorage.setItem("coffee-shop-user", JSON.stringify(userData));
sessionStorage.removeItem("login_phone");
sessionStorage.removeItem("login_role");
router.push(role === "manager" ? "/manager" : "/");
} else {
const errorCode = (await res.text().catch(() => "")).trim();
const msg =
errorCode === "InvalidOTP"
? "Incorrect or expired OTP code"
: "An error occurred, please try again";
setErrors({ otp: msg, general: "" });
}
} catch {
setErrors({ otp: "", general: "Unable to connect, please try again" });
} finally {
setIsLoading(false);
}
};
if (!phone) return null;
return (
<div className="bg-background flex min-h-screen items-center justify-center px-4 py-8">
<div className="w-full max-w-md rounded-2xl bg-white p-8 shadow-lg">
{/* Logo & Shop Name */}
<div className="mb-8 flex flex-col items-center">
<div className="relative mb-4 h-20 w-20">
<Image
src={SHOP_INFO.logo}
alt={SHOP_INFO.name}
fill
className="object-contain"
sizes="80px"
priority
/>
</div>
<h1 className="mb-1 text-2xl font-bold text-(--color-primary-dark)">
{SHOP_INFO.name}
</h1>
<p className="text-sm text-(--color-text-muted)">
Verify your phone number
</p>
</div>
{errors.general && <ErrorMessageLogin message={errors.general} />}
<form onSubmit={handleSubmit} className="space-y-5">
{/* Info */}
<div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
<p className="text-sm text-blue-800">
<i className="fa-solid fa-circle-info mr-2"></i>
OTP code sent to <strong>{phone}</strong>
</p>
</div>
{/* OTP Input */}
<div>
<label
htmlFor="otp"
className="mb-2 block text-sm font-medium text-(--color-text-secondary)"
>
OTP code
</label>
<div className="relative">
<i className="fa-solid fa-key absolute top-1/2 left-4 hidden -translate-y-1/2 text-(--color-text-muted) lg:block"></i>
<input
id="otp"
type="text"
value={otp}
onChange={(e) => {
setOtp(e.target.value);
setErrors({ otp: "", general: "" });
}}
placeholder="Enter OTP code"
maxLength={6}
disabled={isLoading}
className={`text-foreground focus:ring-opacity-20 w-full rounded-xl border bg-white px-4 py-3 text-center text-lg tracking-widest transition-all duration-150 outline-none placeholder:text-sm placeholder:tracking-normal placeholder:text-(--color-text-muted) focus:border-(--color-primary) focus:ring-2 focus:ring-(--color-primary) disabled:opacity-60 lg:pl-11 ${errors.otp ? "border-red-400" : "border-(--color-border)"}`}
/>
</div>
{errors.otp && (
<ErrorMessageLogin message={errors.otp} type="secondary" />
)}
</div>
{/* Buttons */}
<div className="space-y-3 pt-2">
<Button
variant="primaryNoBorder"
type="submit"
style="login"
size="lg"
disabled={isLoading}
>
{isLoading ? (
<>
<i className="fa-solid fa-spinner fa-spin mr-2"></i>
Processing...
</>
) : (
"Sign in"
)}
</Button>
<button
type="button"
onClick={() => router.push("/login")}
className="flex w-full items-center justify-center rounded-xl border-2 border-(--color-primary) bg-white py-3 font-semibold text-(--color-primary) transition-all duration-150 hover:bg-(--color-primary) hover:text-white active:scale-98"
>
Change phone number
</button>
</div>
</form>
</div>
</div>
);
}