import { useForm } from "@tanstack/react-form";
import { toast } from "sonner";

import { signInSchema, signUpSchema } from "../shared/forms";
import { authClient } from "./auth-client";

type AuthFormOptions = {
  readonly onSuccess?: () => void;
};

export const useSignInForm = ({ onSuccess }: AuthFormOptions = {}) =>
  useForm({
    defaultValues: { email: "", password: "" },
    onSubmit: async ({ formApi, value }) => {
      await authClient.signIn.email(
        { email: value.email.trim(), password: value.password },
        {
          onError: ({ error }) => {
            toast.error(error.message || error.statusText);
          },
          onSuccess: () => {
            formApi.reset();
            toast.success("Signed in successfully");
            onSuccess?.();
          },
        },
      );
    },
    validators: { onSubmit: signInSchema },
  });

export const useSignUpForm = ({ onSuccess }: AuthFormOptions = {}) =>
  useForm({
    defaultValues: { confirmPassword: "", email: "", name: "", password: "" },
    onSubmit: async ({ formApi, value }) => {
      await authClient.signUp.email(
        { email: value.email.trim(), name: value.name.trim(), password: value.password },
        {
          onError: ({ error }) => {
            toast.error(error.message || error.statusText);
          },
          onSuccess: () => {
            formApi.reset();
            toast.success("Account created successfully");
            onSuccess?.();
          },
        },
      );
    },
    validators: { onSubmit: signUpSchema },
  });
