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

export const ResetPasswordForm = () => {
  const [loading, setLoading] = createSignal(false);
  const [errors, setErrors] = createSignal<ActionError>();
  let email_form: HTMLFormElement;
  const send = async (form: SubmitEvent) => {
    form.preventDefault();
    setLoading(true);
    setErrors();

    try {
      const formData = new FormData(email_form);
      const { data, error } = await actions.forgotPassword(formData);

      setErrors(error);

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

      if (!error) {
        email_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) => (email_form = e)}
        class="grid gap-5 md:gap-10 max-w-sm mx-auto"
      >
        <FormGroup
          name="password"
          label="Password"
          type={"password"}
          placeholder={"Password"}
          className="grow"
          error={() => getFormErrors("password", errors())}
        />
        <FormGroup
          name="password"
          label="Confirm Password"
          type={"password"}
          placeholder={"Password Again"}
          className="grow"
          error={() => getFormErrors("confirm_password", errors())}
        />

        <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" : "Submit"}
          </button>
        </div>
      </form>
    </>
  );
};
