import { useState } from "react";
import { toast } from "react-hot-toast";
import { useAuth } from "@web/src/providers/auth-provider";
import type { LoginFormData } from "./login";
import type { RegisterFormData } from "./register";

export const useAuthForm = () => {
    const [showLogin, setShowLogin] = useState(true);
    const [isLoading, setIsLoading] = useState(false);
    const { login, signup } = useAuth();

    const toggleForm = () => setShowLogin(!showLogin);

    const handleLogin = async (data: LoginFormData) => {
        try {
            setIsLoading(true);
            await login(data.username, data.password);
            toast.success("登录成功!");
        } catch (err: any) {
            toast.error(err?.response?.data?.message || "用户名或密码错误");
        } finally {
            setIsLoading(false);
        }
    };

    const handleRegister = async (data: RegisterFormData) => {
        try {
            setIsLoading(true);
            await signup(data);
            toast.success("注册成功!");
            setShowLogin(true);
        } catch (err: any) {
            toast.error(err?.response?.data?.message || "注册失败");
        } finally {
            setIsLoading(false);
        }
    };

    return {
        showLogin,
        isLoading,
        toggleForm,
        handleLogin,
        handleRegister
    };
};
