import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/ThemeService";
import type { CreateThemeType, UpdateThemeValueType } from "../type/Types";

export const useGetThemes = () => {
  return useQuery({
    queryKey: ["themes"],
    queryFn: api.getThemes,
  });
};

export const useCreateTheme = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createTheme,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["themes"] });
    },
  });
};

export const useGetThemeById = (id: string) => {
  return useQuery({
    queryKey: ["theme", id],
    queryFn: () => api.getThemeById(id),
    enabled: !!id,
  });
};

export const useUpdateTheme = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateThemeType }) =>
      api.updateTheme(id, params),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["theme"] });
      queryClient.invalidateQueries({ queryKey: ["themes"] });
    },
  });
};

export const useDeleteTheme = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteTheme,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["themes"] });
    },
  });
};

export const useGetThemeValues = (id: string) => {
  return useQuery({
    queryKey: ["theme-values", id],
    queryFn: () => api.getThemeValues(id),
    enabled: !!id,
  });
};

export const useCreateThemeValue = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createThemeValue,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["theme-values"] });
    },
  });
};

export const useUpdateThemeValue = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      params,
    }: {
      id: string;
      params: UpdateThemeValueType;
    }) => api.updateThemeValue(id, params),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["theme-values"] });
    },
  });
};

export const useDeleteThemeValue = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteThemeValue,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["theme-values"] });
    },
  });
};
