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

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

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

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

  const mutation = useMutation<ResponseType, Error, RequestType>({
    mutationFn: async ({ form }) => {
      console.log("🚀 CLIENT: Creating workspace...", { form });
      
      try {
        const response = await client.api.workspaces["$post"]({ form });
        
        console.log("🚀 CLIENT: Response status:", response.status);
        console.log("🚀 CLIENT: Response ok:", response.ok);

        if (!response.ok) {
          const errorData = await response.text();
          console.log("🚀 CLIENT: Error response:", errorData);
          throw new Error(`Failed to create workspace: ${response.status} - ${errorData}`);
        }

        const result = await response.json();
        console.log("🚀 CLIENT: Success response:", result);
        return result;
      } catch (error) {
        console.error("🚀 CLIENT: Error creating workspace:", error);
        throw error;
      }
    },
    onSuccess: (data) => {
      console.log("🚀 CLIENT: Workspace created successfully:", data);
      toast.success("Workspace created");

      router.refresh();
      queryClient.invalidateQueries({ queryKey: ["workspaces"] });
    },
    onError: (error) => {
      console.error("🚀 CLIENT: Workspace creation failed:", error);
      toast.error(`Failed to create workspace: ${error.message}`);
    },
  });

  return mutation;
};
