import { json, redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node"; import { Form, useActionData, useLoaderData, useNavigation, useSearchParams } from "@remix-run/react"; import { useState, useEffect, useRef } from "react"; import { cn } from "~/lib/utils"; import { Button } from "~/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"; import { Input } from "~/components/ui/input"; import { Alert, AlertDescription } from "~/components/ui/alert"; import { Shield, Mail, Clock, CheckCircle, AlertCircle, ArrowLeft, RefreshCw, Loader2 } from "lucide-react"; interface LoaderData { email: string; otpSentAt: string; expiryMinutes: number; } interface OTPActionData { success: boolean; message?: string; otpSentAt?: string; errors?: { otp?: string; general?: string; }; } export const loader = async ({ request }: LoaderFunctionArgs): Promise => { const url = new URL(request.url); const email = url.searchParams.get("email"); if (!email) { return redirect("/sys-rijig-administrator/sign-infirst"); } return json({ email, otpSentAt: new Date().toISOString(), expiryMinutes: 5 }); }; export const action = async ({ request }: ActionFunctionArgs): Promise => { const formData = await request.formData(); const otp = formData.get("otp") as string; const email = formData.get("email") as string; const action = formData.get("_action") as string; if (action === "resend") { console.log("Resending OTP to:", email); return json({ success: true, message: "Kode OTP baru telah dikirim ke email Anda", otpSentAt: new Date().toISOString() }); } if (action === "verify") { const errors: { otp?: string; general?: string } = {}; if (!otp || otp.length !== 4) { errors.otp = "Kode OTP harus 4 digit"; } else if (!/^\d{4}$/.test(otp)) { errors.otp = "Kode OTP hanya boleh berisi angka"; } if (Object.keys(errors).length > 0) { return json({ errors, success: false }, { status: 400 }); } if (otp === "1234") { return redirect("/sys-rijig-adminpanel/dashboard"); } return json( { errors: { otp: "Kode OTP tidak valid atau sudah kedaluwarsa" }, success: false }, { status: 401 } ); } return json( { errors: { general: "Aksi tidak valid" }, success: false }, { status: 400 } ); }; export default function AdminVerifyOTP() { const { email, otpSentAt, expiryMinutes } = useLoaderData(); const actionData = useActionData(); const navigation = useNavigation(); const [searchParams] = useSearchParams(); const [otp, setOtp] = useState(["", "", "", ""]); const [timeLeft, setTimeLeft] = useState(expiryMinutes * 60); const [canResend, setCanResend] = useState(false); const inputRefs = useRef<(HTMLInputElement | null)[]>([]); const isSubmitting = navigation.state === "submitting"; const isResending = navigation.formData?.get("_action") === "resend"; const isVerifying = navigation.formData?.get("_action") === "verify"; useEffect(() => { const timer = setInterval(() => { setTimeLeft((prev) => { if (prev <= 1) { setCanResend(true); return 0; } return prev - 1; }); }, 1000); return () => clearInterval(timer); }, []); useEffect(() => { if (actionData?.success && actionData?.otpSentAt) { setTimeLeft(expiryMinutes * 60); setCanResend(false); } }, [actionData, expiryMinutes]); const handleOtpChange = (index: number, value: string) => { if (!/^\d*$/.test(value)) return; const newOtp = [...otp]; newOtp[index] = value; setOtp(newOtp); if (value && index < 3) { inputRefs.current[index + 1]?.focus(); } }; const handleKeyDown = (index: number, e: React.KeyboardEvent) => { if (e.key === "Backspace" && !otp[index] && index > 0) { inputRefs.current[index - 1]?.focus(); } }; const handlePaste = (e: React.ClipboardEvent) => { e.preventDefault(); const pastedText = e.clipboardData.getData("text"); const digits = pastedText.replace(/\D/g, "").slice(0, 4); if (digits.length === 4) { const newOtp = digits.split(""); setOtp(newOtp); inputRefs.current[3]?.focus(); } }; const formatTime = (seconds: number) => { const mins = Math.floor(seconds / 60); const secs = seconds % 60; return `${mins}:${secs.toString().padStart(2, "0")}`; }; const maskedEmail = email.replace(/(.{2})(.*)(@.*)/, "$1***$3"); return (
Verifikasi Email

Masukkan kode OTP 4 digit yang telah dikirim ke

{maskedEmail}

{/* Success Alert */} {actionData?.success && actionData?.message && ( {actionData.message} )} {/* Error Alert */} {actionData?.errors?.otp && ( {actionData.errors.otp} )} {/* OTP Input Form */}
{/* OTP Input Fields */}
{otp.map((digit, index) => ( (inputRefs.current[index] = el)} type="text" maxLength={1} value={digit} onChange={(e) => handleOtpChange(index, e.target.value)} onKeyDown={(e) => handleKeyDown(index, e)} onPaste={handlePaste} className={cn( "w-12 h-12 text-center text-lg font-bold", actionData?.errors?.otp && "border-red-500" )} autoFocus={index === 0} /> ))}
{/* Timer */}
{timeLeft > 0 ? (
Kode kedaluwarsa dalam {formatTime(timeLeft)}
) : (
Kode OTP telah kedaluwarsa
)}
{/* Verify Button */}
{/* Resend OTP */}

Tidak menerima kode?

{/* Back to Login */} {/* Demo Info */}

Demo OTP:

Gunakan kode:{" "} 1234

Atau tunggu countdown habis untuk test resend

{/* Footer */}

Sistem Pengelolaan Sampah Terpadu

); }