import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/services/api'
import type { ReportMeta, ICDImportResponse } from '@/types'

interface ReportsListResponse {
  items: ReportMeta[]
  total: number
}

export function useReports(reportTypePrefix?: string) {
  return useQuery({
    queryKey: ['reports', reportTypePrefix ?? 'all'],
    queryFn: () =>
      api.get<ReportsListResponse>('/reports/list', {
        params: reportTypePrefix ? { report_type_prefix: reportTypePrefix } : undefined,
      }).then(r => r.data),
  })
}

export function useGenerateReport() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (params: { jahr: number; kw: number; report_type?: string }) =>
      api.post<ReportMeta>('/reports/generate', null, { params }).then(r => r.data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['reports'] })
    },
  })
}

export function useGenerateWochenuebersicht() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (params: { export_type: string; jahr: number; kw_von: number; kw_bis: number }) =>
      api.post<ReportMeta>('/reports/wochenuebersicht/generate', null, { params }).then(r => r.data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['reports'] })
    },
  })
}

export function useUploadWochenuebersichtIcd() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (file: File) => {
      const formData = new FormData()
      formData.append('file', file)
      return api.post<ICDImportResponse>('/reports/wochenuebersicht/upload-icd', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then(r => r.data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cases'] })
    },
  })
}

export function useDeleteReports() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (ids: number[]) =>
      api.delete('/reports/delete', { data: ids }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['reports'] })
    },
  })
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useReportData(reportId: number | null) {
  return useQuery({
    queryKey: ['report-data', reportId],
    queryFn: () =>
      api.get<Record<string, any>>(`/reports/${reportId}/data`).then(r => r.data),
    enabled: reportId !== null,
  })
}
