import React, { useState, useCallback } from 'react'; import axios from 'axios'; const FlashlightOnIcon = () => ( ); const FlashlightOffIcon = () => ( ); const LoginForm = ({ toggleForm, onSuccess }) => { const [loginMode, setLoginMode] = useState('email'); // 'email' or 'whatsapp' const [identifier, setIdentifier] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const [showPassword, setShowPassword] = useState(false); const [emailError, setEmailError] = useState(''); const validateEmail = (email) => { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return regex.test(email); }; const handleIdentifierChange = (e) => { let value = e.target.value; if (loginMode === 'email') { if (!validateEmail(value) && value.length > 0) { setEmailError('Please enter a valid email address.'); } else { setEmailError(''); } } else { setEmailError(''); if (value.startsWith('0')) { value = value.substring(1); } value = value.replace(/[^0-9]/g, ''); } setIdentifier(value); }; const handleLogin = async (e) => { e.preventDefault(); if (loginMode === 'email' && emailError) { setError('Please fix the errors before submitting.'); return; } setLoading(true); setError(''); const finalIdentifier = loginMode === 'whatsapp' ? `62${identifier}` : identifier; try { const response = await axios.post('https://api.karyamanswasta.my.id/webhook/login/adventure', { identifier: finalIdentifier, password, }); const { token } = response.data; localStorage.setItem('authToken', token); console.log('Login successful, token:', token); onSuccess(); // Call onSuccess to reset the form } catch (err) { setError(err.response?.data?.message || 'Login failed. Please check your credentials.'); } finally { setLoading(false); } }; const handleModeChange = useCallback((mode) => { setLoginMode(mode); setIdentifier(''); setPassword(''); setEmailError(''); setShowPassword(false); setError(''); }, []); const togglePasswordVisibility = useCallback(() => { setShowPassword(prev => !prev); }, []); return ( <>
Sign in to continue your adventure