"use client"; import { CheckCircle, KeyRound, Loader2, Shield } from "lucide-react"; import { useTranslation } from "react-i18next"; import { motion } from "framer-motion"; import { sendEmailOTP, sendPhoneOTP, verifyEmail, verifyPhone, getOwnerByUserId, getCustomerByUserId } from "@/app/utils/api"; import AuthService from "@/app/services/AuthService"; import { useState } from "react"; import { useRouter } from "next/navigation"; import toast from "react-hot-toast"; export default function OtpComponent({ isLoading, setIsLoading, isSuccess, setIsSuccess, loginMethod, formData, setStep }) { const { t } = useTranslation(); const router = useRouter(); const [otpCode, setOtpCode] = useState(""); const [otpError, setOtpError] = useState(""); const handleVerifyOTP = async (e) => { e.preventDefault(); if (!otpCode || otpCode.length < 4) { setOtpError(t("otpRequired")); return; } setIsLoading(true); setOtpError(""); try { const verifyFn = loginMethod === "email" ? verifyEmail : verifyPhone; const result = await verifyFn(otpCode); if (result?.ok) { try { await AuthService.cacheCurrentUser(getOwnerByUserId, getCustomerByUserId); console.log("Decoded:", AuthService.decodeToken()); console.log("User:", AuthService.getUser()); } catch (err) { console.warn("Failed to cache user", err); } } setIsSuccess(true); toast.success(t("verifySuccess")); setTimeout(() => { router.push("/"); }, 1500); } catch (err) { console.error("[OTP] Error:", err); setOtpError(err.message || t("verifyError")); } finally { setIsLoading(false); } }; const resendOTP = async () => { try { if (loginMethod === "email") { await sendEmailOTP(); } else { await sendPhoneOTP(); } toast.success(t("resendSuccess"), { style: { background: "#dcfce7", color: "#166534" }, }); } catch (err) { console.error("[OTP] Resend failed:", err); toast.error(t("resendFailed")); } }; return (

{t("sendOTPTo")}{" "} {formData?.credential}

{ setOtpCode(e.target.value); if (otpError) setOtpError(""); }} className={`w-full px-4 py-4 bg-gray-800 border rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent text-white text-center text-2xl tracking-[0.5em] placeholder-gray-500 transition-all ${ otpError ? "border-red-500" : "border-gray-700" }`} placeholder="______" maxLength={6} dir="ltr" /> {otpError && ( {otpError} )}
{isLoading ? ( <> {t("verifying")} ) : isSuccess ? ( <> {t("success")} ) : ( <> {t("verify")} )}
); }