import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { productsApi, Product, PaginationParams } from '@/services/api/crm.api';
import { useToast } from '@/hooks/use-toast';

export function useProducts(params?: PaginationParams & { brandId?: string }) {
  return useQuery({
    queryKey: ['products', params],
    queryFn: () => productsApi.getAll(params).then((res) => res.data),
  });
}

export function useProduct(id: string) {
  return useQuery({
    queryKey: ['products', id],
    queryFn: () => productsApi.getById(id).then((res) => res.data),
    enabled: !!id,
  });
}

export function useProductsByBrand(brandId: string) {
  return useQuery({
    queryKey: ['products', 'brand', brandId],
    queryFn: () => productsApi.getByBrand(brandId).then((res) => res.data),
    enabled: !!brandId,
  });
}

export function useCreateProduct() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (data: Partial<Product>) => productsApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
      toast({ title: 'Producto creado exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al crear producto',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

export function useUpdateProduct() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Product> }) =>
      productsApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
      toast({ title: 'Producto actualizado exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al actualizar producto',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

export function useDeleteProduct() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (id: string) => productsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
      toast({ title: 'Producto eliminado exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al eliminar producto',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}
