import { useForm } from "@tanstack/react-form";
import { useToast } from "heroui-native";

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

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

export const useNativeSignInForm = ({ onSuccess }: AuthFormOptions = {}) => {
  const { toast } = useToast();

  return useForm({
    defaultValues: { email: "", password: "" },
    onSubmit: async ({ formApi, value }) => {
      await authClient.signIn.email(
        { email: value.email.trim(), password: value.password },
        {
          onError: ({ error }) => {
            toast.show({ label: error.message || "Failed to sign in", variant: "danger" });
          },
          onSuccess: () => {
            formApi.reset();
            toast.show({ label: "Signed in successfully", variant: "success" });
            onSuccess?.();
          },
        },
      );
    },
    validators: { onSubmit: signInSchema },
  });
};

export const useNativeSignUpForm = ({ onSuccess }: AuthFormOptions = {}) => {
  const { toast } = useToast();

  return 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.show({
              label: error.message || "Failed to create account",
              variant: "danger",
            });
          },
          onSuccess: () => {
            formApi.reset();
            toast.show({ label: "Account created successfully", variant: "success" });
            onSuccess?.();
          },
        },
      );
    },
    validators: { onSubmit: signUpSchema },
  });
};

export { getErrorMessage };
