import { useState } from 'react';
import { ScuteAuth, getMeaningfulError } from "@scute/js-core";
const useAuthForm = () => {
const [errors, setErrors] = useState<Record<string, string>>({});
const [isLoading, setIsLoading] = useState(false);
const [generalError, setGeneralError] = useState<string>("");
const validateField = (name: string, value: string): string => {
switch (name) {
case 'email':
if (!value) return 'Email is required';
if (!/\S+@\S+\.\S+/.test(value)) return 'Email format is invalid';
return '';
case 'password':
if (!value) return 'Password is required';
if (value.length < 8) return 'Password must be at least 8 characters';
return '';
default:
return '';
}
};
const handleSubmit = async (formData: { email: string; password: string }) => {
// Clear previous errors
setErrors({});
setGeneralError("");
// Validate all fields
const fieldErrors: Record<string, string> = {};
Object.entries(formData).forEach(([key, value]) => {
const error = validateField(key, value);
if (error) fieldErrors[key] = error;
});
if (Object.keys(fieldErrors).length > 0) {
setErrors(fieldErrors);
return;
}
setIsLoading(true);
try {
await authenticateWithRetry(formData);
// Handle successful authentication
} catch (error: any) {
const errorResult = getMeaningfulError(error);
// Handle field-specific errors
if (error.code === "identifier-invalid") {
setErrors({ email: "Please enter a valid email address" });
} else if (error.code === "identifier-not-recognized") {
setErrors({ email: "This email address is not recognized" });
} else {
// Handle general errors
setGeneralError(errorResult.message || "Authentication failed. Please try again.");
}
// Log error for debugging
console.error("Form submission error:", {
error: errorResult.message,
isFatal: errorResult.isFatal,
code: error.code,
formData: { email: formData.email } // Don't log password
});
} finally {
setIsLoading(false);
}
};
return {
errors,
generalError,
isLoading,
handleSubmit,
validateField
};
};