import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";

const useAuth = () => {
    const [validated, setValidated] = useState(false);
    const [loading, setLoading] = useState(true);
    const [username, setUsername] = useState("");
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const router = useRouter();

    const validate = useCallback(async () => {
        setLoading(true);
        try {
            const token = Cookies.get("token");
            if (!token) {
                setLoading(false);
                setValidated(false);
                router.push("/");
                return "Invalid";
            }
            
            const response = await axios.post("/api/user/validate", { token });
            if (response.data.message === "Valid") {
                setValidated(true);
                setUsername(response.data.username);
                setName(response.data.name);
                setEmail(response.data.email);
                return "Validated";
            } else {
                setValidated(false);
                Cookies.remove("token");
                router.push("/");
                return "Invalid";
            }
        } catch (error) {
            console.error("Validation error:", error);
            setValidated(false);
            Cookies.remove("token");
            router.push("/");
            return "Invalid";
        } finally {
            setLoading(false);
        }
    }, [router]);

    useEffect(() => {
        validate();
    }, [validate]);

    return {
        validated,
        loading,
        username,
        name,
        email,
        validate
    };
}

export default useAuth;