import React, { useState, useEffect } from 'react'; import axios from 'axios'; const OtpForm = ({ onSuccess }) => { const [emailOtp, setEmailOtp] = useState(''); const [whatsappOtp, setWhatsappOtp] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(''); const [loading, setLoading] = useState(false); const [timer, setTimer] = useState(60); // 1 minute in seconds useEffect(() => { if (timer > 0) { const interval = setInterval(() => { setTimer(prev => prev - 1); }, 1000); return () => clearInterval(interval); } }, [timer]); const formatTime = (seconds) => { const minutes = Math.floor(seconds / 60); const remainingSeconds = seconds % 60; return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`; }; const handleOtpChange = (setter) => (e) => { const value = e.target.value.replace(/[^0-9]/g, ''); setter(value); }; const handleResend = async () => { setLoading(true); setError(''); setSuccess(''); try { await axios.post('https://api.karyamanswasta.my.id/webhook/otp-request/adventure'); setSuccess('A new OTP has been sent.'); setTimer(60); // Reset timer } catch (err) { setError('Failed to resend OTP.'); } finally { setLoading(false); } }; const handleVerify = async (e) => { e.preventDefault(); setLoading(true); setError(''); setSuccess(''); try { await axios.post('https://api.karyamanswasta.my.id/webhook/otp-verify/adventure', { emailOtp, whatsappOtp, }); setSuccess('Account verified successfully! Redirecting to login...'); setTimeout(() => { onSuccess(); }, 2000); } catch (err) { setError(err.response?.data?.message || 'OTP verification failed.'); } finally { setLoading(false); } }; const isFormValid = emailOtp.length >= 6 && whatsappOtp.length >= 6; return ( <>
Enter the OTP sent to your email and WhatsApp
{formatTime(timer)}