import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateVisionPayload,
  VisionItem,
  VisionResponse,
} from "../types/visionType";
import { VisionService } from "../services/visionService";
import { param } from "jquery";

export interface VisionParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  isActive?: boolean;
}
export const useVision = (params?: VisionParams, id?: string) => {
  const queryClient = useQueryClient();

  const {
    data: singleItem,
    isLoading,
    error,
  } = useQuery<VisionItem>({
    queryKey: ["Vision", id],
    queryFn: async () => {
      const resp: VisionItem = await VisionService.getItem(id || "");

      return resp;
    },
    enabled: !!id,
  });
  const { data: items, refetch } = useQuery<VisionResponse>({
    queryKey: ["Vision1", params],
    queryFn: async () => {
      const resp: VisionResponse = await VisionService.getItems(params!);

      return resp;
    },
  });
  const createMutation = useMutation({
    mutationFn: async (payload: { data: CreateVisionPayload }) => {
      // Step 1: Create the initial item record
      const createResponse = await VisionService.createItem(payload.data);

      if (!createResponse.id) {
        throw new Error("Failed to create Vision item");
      }

      return createResponse;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["Vision1", params],
      });
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: string;
      data: Partial<CreateVisionPayload>;
    }) => VisionService.updateItem(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Vision1", params] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: VisionService.deleteItem,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Vision1", params] });
    },
  });
  return {
    items: items?.items,
    singleItem: singleItem,
    count: items?.count,
    isLoading,
    error,
    createItem: createMutation.mutateAsync,
    updateItem: updateMutation.mutateAsync,
    deleteItem: deleteMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending,
    refetch,
  };
};
