mediahub-fe/app/[locale]/auth/page.tsx

123 lines
3.2 KiB
TypeScript

"use client";
import React, { useState } from "react";
import { AuthLayout } from "@/components/auth/auth-layout";
import { LoginForm } from "@/components/auth/login-form";
import { EmailSetupForm } from "@/components/auth/email-setup-form";
import { OTPForm } from "@/components/auth/otp-form";
import { LoginFormData } from "@/types/auth";
import { useAuth, useEmailValidation } from "@/hooks/use-auth";
import { toast } from "sonner";
type AuthStep = "login" | "email-setup" | "otp";
const AuthPage = ({ params: { locale } }: { params: { locale: string } }) => {
const [currentStep, setCurrentStep] = useState<AuthStep>("login");
const [loginCredentials, setLoginCredentials] =
useState<LoginFormData | null>(null);
const { validateEmail } = useEmailValidation();
const { login } = useAuth();
const handleLoginSuccess = async (data: LoginFormData) => {
setLoginCredentials(data);
// Check email validation to determine next step
try {
const result = await validateEmail(data);
switch (result) {
case "skip":
handleOTPSuccess();
break;
case "setup":
setCurrentStep("email-setup");
break;
case "otp":
setCurrentStep("otp");
break;
case "success":
// The login hook will handle navigation automatically
break;
default:
toast.error("Unexpected response from email validation");
}
} catch (error: any) {
toast.error(error.message || "Email validation failed");
}
};
const handleLoginError = (error: string) => {
toast.error(error);
};
const handleEmailSetupSuccess = () => {
setCurrentStep("otp");
};
const handleEmailSetupError = (error: string) => {
toast.error(error);
};
const handleEmailSetupBack = () => {
setCurrentStep("login");
};
const handleOTPSuccess = async () => {
if (loginCredentials) {
try {
await login(loginCredentials);
// Navigation handled by login
} catch (error: any) {
toast.error(error.message || "Login failed after OTP verification");
}
}
};
const handleOTPError = (error: string) => {
toast.error(error);
};
const handleOTPResend = () => {
toast.info("OTP resent successfully");
};
const renderCurrentStep = () => {
switch (currentStep) {
case "login":
return (
<LoginForm
onSuccess={handleLoginSuccess}
onError={handleLoginError}
/>
);
case "email-setup":
return (
<EmailSetupForm
loginCredentials={loginCredentials}
onSuccess={handleEmailSetupSuccess}
onError={handleEmailSetupError}
onBack={handleEmailSetupBack}
/>
);
case "otp":
return (
<OTPForm
loginCredentials={loginCredentials}
onSuccess={handleOTPSuccess}
onError={handleOTPError}
onResend={handleOTPResend}
/>
);
default:
return (
<LoginForm
onSuccess={handleLoginSuccess}
onError={handleLoginError}
/>
);
}
};
return <AuthLayout>{renderCurrentStep()}</AuthLayout>;
};
export default AuthPage;