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 LoginForm = () => {
  const [loading, setLoading] = createSignal(false);
  const [errors, setErrors] = createSignal<ActionError>();
  let login_form: HTMLFormElement;
  const send = async (form: SubmitEvent) => {
    form.preventDefault();
    setLoading(true);
    setErrors();

    try {
      const formData = new FormData(login_form);
      const { data, error } = await actions.login(formData);
      setLoading(false);

      setErrors(error);

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

      if (!error) {
        console.log({ data });
        login_form.reset();
        return navigate("/dashboard");
      }
    } catch (error) {
      console.log({ 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) => (login_form = e)}
        class="grid gap-5 md:gap-10 max-w-sm mx-auto"
      >
        <FormGroup
          name="email"
          label="Email"
          type={"email"}
          placeholder={"Email"}
          className="grow"
          error={() => getFormErrors(["email"], errors())}
        />
        <FormGroup
          name="password"
          type={"password"}
          label="Password"
          placeholder={"Password"}
          className="grow"
          hint={
            <small class="ms-auto">
              <a href="/dashboard/forgot-password" class="text-blue-950">
                Forgot password?
              </a>
            </small>
          }
          error={() => getFormErrors(["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" : "Login"}
          </button>
        </div>
      </form>
    </>
  );
};
