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

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

  const handleSubmit = async (e, formData) => {
    e.preventDefault();
    setErrors({});

    let newErrors = {};

    if (formData.name.length < 3) {
      newErrors.name = "Nama minimal 3 karakter";
    }
    if (!Helpers.validateEmail(formData.email)) {
      newErrors.email = "Email tidak valid";
    }
    if (formData.nrp.length < 10) {
      newErrors.nrp = "NRP minimal 10 digit";
    }
    if (!Helpers.validatePhone(formData.phone)) {
      newErrors.phone = "Nomor tidak valid";
    }
    if (formData.password.length < 8) {
      newErrors.password = "Password minimal 8 karakter";
    }
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = "Password tidak cocok";
    }

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

    setLoading(true);

    try {
      await ApiUtils.post(CONFIG.API_ENDPOINTS.REGISTER, {
        name: formData.name,
        email: formData.email,
        nrp: formData.nrp,
        phone: formData.phone,
        password: formData.password,
      });

      showToast("Registrasi berhasil! Mengalihkan ke login...", "success");

      setTimeout(() => {
        window.location.href = "/login";
      }, 2000);
    } catch (error) {
      showToast(error.message || "Registrasi gagal!", "error");
    } finally {
      setLoading(false);
    }
  };

  return { handleSubmit };
};
