import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  listDeclaraciones,
  createDeclaracion,
  uploadComprobantePago,
  deleteDeclaracion,
  downloadDeclaracionPdf,
  downloadBlob,
  type CreateDeclaracionData,
} from '../api/declaraciones';
import { useTenantViewStore } from '../../stores/tenant-view-store';

export function useDeclaraciones(fechaDesde?: string, fechaHasta?: string, contribuyenteId?: string | null) {
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  return useQuery({
    queryKey: ['declaraciones', fechaDesde, fechaHasta, contribuyenteId ?? 'all', viewingTenantId],
    queryFn: () => listDeclaraciones(fechaDesde, fechaHasta, contribuyenteId),
  });
}

export function useCreateDeclaracion() {
  const qc = useQueryClient();
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  return useMutation({
    mutationFn: (data: CreateDeclaracionData) => createDeclaracion(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['declaraciones'] });
      qc.invalidateQueries({ queryKey: ['alertas'] });
      qc.invalidateQueries({ queryKey: ['alertas-manuales'] });
      qc.invalidateQueries({ queryKey: ['alertas-automaticas'] });
      qc.invalidateQueries({ queryKey: ['eventos'] });
    },
  });
}

export function useUploadComprobantePago() {
  const qc = useQueryClient();
  const viewingTenantId = useTenantViewStore((s) => s.viewingTenantId);
  return useMutation({
    mutationFn: ({ id, pdfBase64, pdfFilename }: { id: number; pdfBase64: string; pdfFilename: string }) =>
      uploadComprobantePago(id, pdfBase64, pdfFilename),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['declaraciones'] });
      qc.invalidateQueries({ queryKey: ['alertas'] });
      qc.invalidateQueries({ queryKey: ['alertas-manuales'] });
      qc.invalidateQueries({ queryKey: ['alertas-automaticas'] });
      qc.invalidateQueries({ queryKey: ['eventos'] });
    },
  });
}

export function useDeleteDeclaracion() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => deleteDeclaracion(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['declaraciones'] }),
  });
}

export function useDownloadDeclaracionPdf() {
  return useMutation({
    mutationFn: async ({ id, variant, filename }: { id: number; variant: 'declaracion' | 'liga' | 'pago'; filename: string }) => {
      const blob = await downloadDeclaracionPdf(id, variant);
      downloadBlob(blob, filename);
    },
  });
}
