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

export function useClients(params?: PaginationParams) {
  return useQuery({
    queryKey: ['clients', params],
    queryFn: () => clientsApi.getAll(params).then((res) => res.data),
  });
}

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

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

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

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

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

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

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