import { getFormErrors } from "@/utils/errors";
import { FormGroup } from "@components/FormGroup";
import Toast from "@utils/toast";
import { actions, type ActionError } from "astro:actions";
import { navigate } from "astro:transitions/client";
import { createSignal } from "solid-js";

export const RegisterForm = () => {
  const [loading, setLoading] = createSignal(false);
  const [errors, setErrors] = createSignal<ActionError>();

  let register_form: HTMLFormElement;
  const send = async (form: SubmitEvent) => {
    form.preventDefault();
    setLoading(true);
    try {
      const formData = new FormData(register_form);
      const { data, error } = await actions.register(formData);

      setErrors(error);

      await Toast.fire({
        icon: "success",
        title: !error ? "Successful" : "Failed",
        text: data?.message ?? errors()?.message,
      });

      if (!error) {
        register_form.reset();
        return navigate("/dashboard");
      }
    } catch (error) {
      await Toast.fire({
        icon: "error",
        title: "Error",
        // @ts-ignore
        text: error.message,
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      <form
        method="post"
        onSubmit={(form) => send(form)}
        ref={(e) => (register_form = e)}
        class="flex flex-col gap-5 md:gap-10 max-w-sm mx-auto"
      >
        <FormGroup
          name="firstName"
          required={true}
          label="First Name"
          placeholder={"First Name"}
          className="grow"
          error={() => getFormErrors(["firstName"], errors())}
        />
        <FormGroup
          name="lastName"
          required={true}
          label="Last Name"
          placeholder={"Last Name"}
          className="grow"
          error={() => getFormErrors(["lastName"], errors())}
        />
        <FormGroup
          name="email"
          required={true}
          label="Email"
          type={"email"}
          placeholder={"Email"}
          className="grow"
          error={() => getFormErrors(["email"], errors())}
        />
        {/* <FormGroup
          name="password"
          required={true}
          type={"password"}
          label="Password"
          placeholder={"Password"}
          className="grow"
        /> */}

        <div class="flex flex-wrap justify-center mt-5">
          <button
            type="submit"
            class="bg-blue-950 rounded-lg text-white p-2 w-[10rem]"
          >
            {loading() ? "...loading" : "Register"}
          </button>
        </div>
      </form>
    </>
  );
};
