import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { TemplateService } from "../services/templateService";
import { LIST_BULLET_RESOURCES_QUERY_KEY } from "@/user-management/services/api/listBulletResources";
import {
  TemplateResource,
  ResourceType,
} from "../TemplateConfiguration/types/templateTypes";

export interface TemplateParams {
  page?: number;
  limit?: number;
  search?: string;
  resourceTypeId?: string;
}

export function useResourceTypes() {
  return useQuery({
    queryKey: ["resourceTypes"],
    queryFn: () => TemplateService.getResourceTypes(),
  });
}

export function useTemplates(params?: TemplateParams) {
  return useQuery({
    queryKey: ["templates", params],
    queryFn: () =>
      TemplateService.getTemplates(params as Record<string, unknown>),
  });
}

export function useTemplate(id: string) {
  return useQuery({
    queryKey: ["templates", id],
    queryFn: () => TemplateService.getTemplate(id),
    enabled: !!id,
  });
}

export function useTemplateWithPresigned(
  resourceTypeId: string,
  templateId: string,
) {
  return useQuery({
    queryKey: ["templates", resourceTypeId, templateId],
    queryFn: () =>
      TemplateService.getTemplateWithPresigned(resourceTypeId, templateId),
    enabled: !!resourceTypeId && !!templateId,
  });
}

export function useTemplateMutations() {
  const queryClient = useQueryClient();

  const createMutation = useMutation({
    mutationFn: async (data: any) => {
      const { fileData, ...templateData } = data;
      const response = await TemplateService.createTemplate(templateData);

      if (fileData?.file && response.presigned && response.id) {
        try {
          await TemplateService.uploadFile(fileData.file, response.presigned);
          await TemplateService.updateUploadStatus(response.id, true);
        } catch (error) {
          console.error("File upload failed:", error);
          throw error;
        }
      }

      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      queryClient.invalidateQueries({ queryKey: LIST_BULLET_RESOURCES_QUERY_KEY });
    },
  });

  const updateMutation = useMutation({
    mutationFn: async (data: any) => {
      const { id, fileData, ...templateData } = data;
      const response = await TemplateService.updateTemplate(id, templateData);

      if (fileData?.file && response.presigned && id) {
        try {
          await TemplateService.uploadFile(fileData.file, response.presigned);
          await TemplateService.updateUploadStatus(id, true);
        } catch (error) {
          console.error("File upload failed:", error);
          throw error;
        }
      }

      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      queryClient.invalidateQueries({ queryKey: LIST_BULLET_RESOURCES_QUERY_KEY });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => TemplateService.deleteTemplate(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      queryClient.invalidateQueries({ queryKey: LIST_BULLET_RESOURCES_QUERY_KEY });
    },
  });

  return {
    create: createMutation,
    update: updateMutation,
    delete: deleteMutation,
  };
}
