import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { InferRequestType, InferResponseType } from "hono";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { signIn } from "next-auth/react";

import { client } from "@/lib/rpc";

type ResponseType = InferResponseType<
  (typeof client.api.users.register)["$post"]
>;
type RequestType = InferRequestType<(typeof client.api.users.register)["$post"]>;

export const useRegister = () => {
  const router = useRouter();
  const queryClient = useQueryClient();

  const mutation = useMutation<ResponseType, Error, RequestType>({
    mutationFn: async ({ json }) => {
      const response = await client.api.users.register["$post"]({ json });

      if (!response.ok) {
        throw new Error("Something went wrong");
      }

      return await response.json();
    },
    onSuccess: async (data, variables) => {
      toast.success("Registered successfully!");
      
      try {
        const result = await signIn("credentials", {
          email: variables.json.email,
          password: variables.json.password,
          redirect: false,
          callbackUrl: "/"
        });

        if (result?.error) {
          throw new Error(result.error);
        }

        router.refresh();
        queryClient.invalidateQueries({ queryKey: ["current"] });
        router.push("/");
      } catch (error) {
        console.error("Error signing in after registration:", error);
        toast.error("Registration successful but couldn't sign in automatically. Please sign in manually.");
      }
    },
    onError: () => {
      toast.error("Failed to register");
    },
  });

  return mutation;
};
