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

export const ProfileForm = (
  user: Partial<User> & { firstName?: string; lastName?: string; id: number },
  self: boolean,
  onSuccess?: Function
) => {
  const [loading, setLoading] = createSignal(false);
  const [errors, setErrors] = createSignal<ActionError>();
  let profile_form: HTMLFormElement;
  const send = async (form: SubmitEvent) => {
    form.preventDefault();
    setLoading(true);
    setErrors();

    try {
      const formData = new FormData(profile_form);
      const { data, error } = await actions.updateProfile(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) {
        onSuccess;
      }
    } catch (error) {
      console.log({ error });
      await Toast.fire({
        icon: "error",
        title: "Error",
        // @ts-ignore
        text: error.message,
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <>
      <form
        onSubmit={(form) => send(form)}
        class="grid gap-5 md:gap-10"
        ref={(e) => (profile_form = e)}
      >
        <input value={user.id} name="id" hidden />
        <input value={self} name="self" hidden />
        <div class="form-grid">
          <FormGroup
            name="firstName"
            required={true}
            value={user?.first_name ?? user?.firstName}
            label="First Name"
            placeholder={"First Name"}
            error={() => getFormErrors(["firstName"], errors())}
            className=""
          />
          <FormGroup
            name="lastName"
            value={user?.last_name ?? user?.lastName}
            required={true}
            label="Last Name"
            placeholder={"Last Name"}
            error={() => getFormErrors(["lastName"], errors())}
            className=""
          />
          <FormGroup
            name="username"
            value={user?.username}
            label="Username"
            placeholder={"Username"}
            error={() => getFormErrors(["username"], errors())}
            className=""
          />
          <div class="sm:col-span-2">
            <FormGroup
              name="email"
              required={true}
              value={user?.email}
              label="Email"
              type={"email"}
              placeholder={"Email"}
              error={() => getFormErrors(["email"], errors())}
            />
          </div>
          <FormGroup
            name="phone"
            value={user?.phone}
            label="Phone"
            type={"tel"}
            placeholder={"Phone"}
            error={() => getFormErrors(["phone"], errors())}
            className=""
          />
          <div class="sm:col-span-2">
            <FormGroup
              name="address"
              value={user?.address}
              label="Address"
              placeholder={"Address"}
              error={() => getFormErrors(["address"], errors())}
            />
          </div>
        </div>

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