import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as alertasApi from '../api/alertas';
import type { AlertaCreate, AlertaUpdate } from '@horux/shared';
import { useContribuyenteStore } from '@/stores/contribuyente-store';

export function useAlertas(filters?: { leida?: boolean; resuelta?: boolean }) {
  const { selectedContribuyenteId } = useContribuyenteStore();

  return useQuery({
    queryKey: ['alertas', filters, selectedContribuyenteId],
    queryFn: () => alertasApi.getAlertas({ ...filters, contribuyenteId: selectedContribuyenteId || undefined }),
  });
}

export function useAlertasAutomaticas() {
  const { selectedContribuyenteId } = useContribuyenteStore();

  return useQuery({
    queryKey: ['alertas-automaticas', selectedContribuyenteId],
    queryFn: () => alertasApi.getAlertasAutomaticas(selectedContribuyenteId || undefined),
  });
}

export function useAlertasStats() {
  return useQuery({
    queryKey: ['alertas-stats'],
    queryFn: alertasApi.getStats,
  });
}

export function useCreateAlerta() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: AlertaCreate) => alertasApi.createAlerta(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alertas'] });
      queryClient.invalidateQueries({ queryKey: ['alertas-stats'] });
    },
  });
}

export function useUpdateAlerta() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: AlertaUpdate }) => alertasApi.updateAlerta(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alertas'] });
      queryClient.invalidateQueries({ queryKey: ['alertas-stats'] });
    },
  });
}

export function useDeleteAlerta() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => alertasApi.deleteAlerta(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alertas'] });
      queryClient.invalidateQueries({ queryKey: ['alertas-stats'] });
    },
  });
}

export function useMarkAllAsRead() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: alertasApi.markAllAsRead,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alertas'] });
      queryClient.invalidateQueries({ queryKey: ['alertas-stats'] });
    },
  });
}
