import { QUERY_KEYS } from "@/utils/query-key";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  getProducts,
  getProduct,
  createProduct,
  updateProduct,
  deleteProduct,
  getProductVariants,
  createProductVariant,
  updateProductVariant,
  deleteProductVariant,
} from "./_requests";
import {
  CreateProductRequest,
  UpdateProductRequest,
  CreateVariantRequest,
  UpdateVariantRequest,
  ProductFilters,
} from "./_models";
import toast from "react-hot-toast";

// Products Hooks
export const useProducts = (filters?: ProductFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PRODUCTS, filters],
    queryFn: () => getProducts(filters),
  });
};

export const useSearchProducts = (filters: ProductFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.SEARCH_PRODUCTS, filters],
    queryFn: () => getProducts(filters),
    enabled: Object.keys(filters).length > 0,
    staleTime: 2 * 60 * 1000, // 2 minutes for search results
  });
};

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

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

  return useMutation({
    mutationKey: [QUERY_KEYS.CREATE_PRODUCT],
    mutationFn: (data: CreateProductRequest) => createProduct(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCTS] });
      toast.success("محصول با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      console.error("Create product error:", error);
      toast.error(error?.message || "خطا در ایجاد محصول");
    },
  });
};

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

  return useMutation({
    mutationKey: [QUERY_KEYS.UPDATE_PRODUCT],
    mutationFn: (data: UpdateProductRequest) => updateProduct(data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCTS] });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT, variables.id.toString()],
      });
      toast.success("محصول با موفقیت ویرایش شد");
    },
    onError: (error: any) => {
      console.error("Update product error:", error);
      toast.error(error?.message || "خطا در ویرایش محصول");
    },
  });
};

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

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

// Product Variants Hooks
export const useProductVariants = (
  productId: string,
  enabled: boolean = true
) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PRODUCT_VARIANTS, productId],
    queryFn: () => getProductVariants(productId),
    enabled: enabled && !!productId,
  });
};

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

  return useMutation({
    mutationKey: [QUERY_KEYS.CREATE_PRODUCT_VARIANT],
    mutationFn: (data: CreateVariantRequest) => createProductVariant(data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: [
          QUERY_KEYS.GET_PRODUCT_VARIANTS,
          variables.product_id?.toString() || "",
        ],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT, variables.product_id?.toString()],
      });
      toast.success("نسخه محصول با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      console.error("Create variant error:", error);
      toast.error(error?.message || "خطا در ایجاد نسخه محصول");
    },
  });
};

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

  return useMutation({
    mutationKey: [QUERY_KEYS.UPDATE_PRODUCT_VARIANT],
    mutationFn: (data: UpdateVariantRequest) => updateProductVariant(data),
    onSuccess: (result) => {
      // We need to get product_id from somewhere, let's invalidate all variants queries
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_VARIANTS],
      });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCTS] });
      toast.success("نسخه محصول با موفقیت ویرایش شد");
    },
    onError: (error: any) => {
      console.error("Update variant error:", error);
      toast.error(error?.message || "خطا در ویرایش نسخه محصول");
    },
  });
};

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

  return useMutation({
    mutationKey: [QUERY_KEYS.DELETE_PRODUCT_VARIANT],
    mutationFn: (variantId: string) => deleteProductVariant(variantId),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_PRODUCT_VARIANTS],
      });
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCTS] });
      toast.success("نسخه محصول با موفقیت حذف شد");
    },
    onError: (error: any) => {
      console.error("Delete variant error:", error);
      toast.error(error?.message || "خطا در حذف نسخه محصول");
    },
  });
};
