// assets/js/pages/auth/useLoginHandlers.js
const useLoginHandlers = (state) => {
  const { setErrors, setLoading, setToast } = state;

  const showToast = (message, type = "info") => {
    setToast({ message, type });
  };

  const handleSubmit = async (e, email, password) => {
    e.preventDefault();

    setErrors({});

    let newErrors = {};
    if (!Helpers.validateEmail(email)) {
      newErrors.email = "Email tidak valid";
    }
    if (password.length < 6) {
      newErrors.password = "Password minimal 6 karakter";
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);

    try {
      const data = await ApiUtils.post(CONFIG.API_ENDPOINTS.LOGIN, {
        email,
        password,
      });

      AuthUtils.setToken(data.data.token);
      AuthUtils.setCurrentUser(data.data.user);

      showToast("Login berhasil! Mengalihkan...", "success");

      setTimeout(() => {
        AuthUtils.redirectBasedOnRole(data.data.user);
      }, 500);
    } catch (error) {
      showToast(error.message || "Email atau password salah!", "error");
    } finally {
      setLoading(false);
    }
  };

  return { handleSubmit };
};
