import { QUERY_KEYS } from "@/utils/query-key";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  getProductOptions,
  getProductOption,
  createProductOption,
  updateProductOption,
  deleteProductOption,
} from "./_requests";
import {
  CreateProductOptionRequest,
  UpdateProductOptionRequest,
  ProductOptionFilters,
} from "./_models";
import toast from "react-hot-toast";

export const useProductOptions = (filters?: ProductOptionFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PRODUCT_OPTIONS, filters],
    queryFn: () => getProductOptions(filters),
  });
};

export const useProductOption = (id: string, enabled: boolean = true) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PRODUCT_OPTION, id],
    queryFn: () => getProductOption(id),
    enabled: enabled && !!id,
  });
};

export const useCreateProductOption = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: [QUERY_KEYS.CREATE_PRODUCT_OPTION],
    mutationFn: (data: CreateProductOptionRequest) => createProductOption(data),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_OPTIONS],
      });
      toast.success("گزینه محصول با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      console.error("Create product option error:", error);
      toast.error(error?.message || "خطا در ایجاد گزینه محصول");
    },
  });
};

export const useUpdateProductOption = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: [QUERY_KEYS.UPDATE_PRODUCT_OPTION],
    mutationFn: (data: UpdateProductOptionRequest) => updateProductOption(data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_OPTIONS],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_OPTION, variables.id.toString()],
      });
      toast.success("گزینه محصول با موفقیت ویرایش شد");
    },
    onError: (error: any) => {
      console.error("Update product option error:", error);
      toast.error(error?.message || "خطا در ویرایش گزینه محصول");
    },
  });
};

export const useDeleteProductOption = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: [QUERY_KEYS.DELETE_PRODUCT_OPTION],
    mutationFn: (id: string) => deleteProductOption(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_OPTIONS],
      });
      toast.success("گزینه محصول با موفقیت حذف شد");
    },
    onError: (error: any) => {
      console.error("Delete product option error:", error);
      toast.error(error?.message || "خطا در حذف گزینه محصول");
    },
  });
};
