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

export function useBrands(params?: PaginationParams & { clientId?: string }) {
  return useQuery({
    queryKey: ['brands', params],
    queryFn: () => brandsApi.getAll(params).then((res) => res.data),
  });
}

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

export function useBrandsByClient(clientId: string) {
  return useQuery({
    queryKey: ['brands', 'client', clientId],
    queryFn: () => brandsApi.getByClient(clientId).then((res) => res.data),
    enabled: !!clientId,
  });
}

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

  return useMutation({
    mutationFn: (data: Partial<Brand>) => brandsApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['brands'] });
      toast({ title: 'Marca creada exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al crear marca',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

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

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Brand> }) =>
      brandsApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['brands'] });
      toast({ title: 'Marca actualizada exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al actualizar marca',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

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

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