import useStatus from "@/twui/components/hooks/useStatus";
import { useCallback, useEffect, useState } from "react";
import { AlertObject, APIReqObject, LoginFormData } from "../types";
import fetchApi from "@moduletrace/datasquirel/dist/client/fetch";
import { APIResponseObject } from "@moduletrace/datasquirel/dist/package-shared/types";
import z, { ZodError } from "zod";
import { EJSON } from "../exports/client-exports";

export default function useLoginForm() {
    const [loginData, setLoginData] = useState<LoginFormData>({});
    const [alert, setAlert] = useState<AlertObject>();
    const { loading, setLoading } = useStatus();

    useEffect(() => {
        setAlert(undefined);
    }, [loginData]);

    const submitLogin = useCallback(async () => {
        if (!loginData.email && !loginData.username) {
            setAlert({ text: `Please Enter a username or email` });
            return;
        }

        const password_schema = z.string().min(6);
        const is_password = password_schema.safeParse(loginData.password || "");

        if (!is_password.success) {
            const error_text =
                `Invalid Password: ` +
                (EJSON.parse(is_password.error.message) as ZodError[])?.[0]
                    .message;

            setAlert({
                text: error_text,
                field_name: "password",
            });
            return;
        }

        setLoading(true);

        try {
            const res = await fetchApi<APIReqObject, APIResponseObject>(
                `/api/auth/login`,
                {
                    method: "POST",
                    body: {
                        ...loginData,
                    },
                },
            );

            if (res.success) {
                window.location.reload();
            } else {
                setAlert({ text: res.msg || `Login Failed` });
                setLoading(false);
            }
        } catch (error) {
            setLoading(false);
        }
    }, [loginData]);

    return {
        loginData,
        setLoginData,
        loading,
        setLoading,
        submitLogin,
        alert,
        setAlert,
    };
}
