import React, { useState } from "react"; import { View, TextInput, ActivityIndicator } from "react-native"; import { useTranslation } from "react-i18next"; import { Button } from "../ui/button"; import Text from "../ui/Text"; import { authClient, useSession } from "../../lib/auth"; import { Block } from "../ui"; type AuthMode = "login" | "register"; type AuthResponse = { data: unknown; error: { message: string } | null }; type SignInFn = (params: { username: string; password: string }) => Promise; type SignUpFn = (params: { email: string; password: string; name: string }) => Promise; const signIn = authClient.signIn as unknown as { username: SignInFn }; const signUp = authClient.signUp as unknown as { email: SignUpFn }; interface AuthFormProps { mode?: AuthMode; onSuccess?: () => void; onModeChange?: (mode: AuthMode) => void; } export function AuthForm({ mode = "login", onSuccess, onModeChange }: AuthFormProps) { const { t } = useTranslation(); const [currentMode, setCurrentMode] = useState(mode); const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const isLogin = currentMode === "login"; const handleSubmit = async () => { if (!username.trim() || !password.trim()) { setError(t("authForm.fillCompleteInfo")); return; } if (!isLogin && !email.trim()) { setError(t("authForm.fillEmail")); return; } setLoading(true); setError(""); try { if (isLogin) { const res = await signIn.username({ username, password }); if (res.error) throw new Error(res.error.message); } else { const res = await signUp.email({ email, password, name: username }); if (res.error) throw new Error(res.error.message); } onSuccess?.(); } catch (e: unknown) { const msg = e instanceof Error ? e.message : (isLogin ? t("authForm.loginFailed") : t("authForm.registerFailed")); setError(msg); } finally { setLoading(false); } }; const toggleMode = () => { const newMode = isLogin ? "register" : "login"; setCurrentMode(newMode); onModeChange?.(newMode); setEmail(""); setError(""); }; return ( {isLogin ? t("authForm.login") : t("authForm.register")} {!isLogin && ( )} {error ? ( {error} ) : null} {isLogin ? t("authForm.noAccountRegister") : t("authForm.haveAccountLogin")} ); } export { useSession };