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

export interface CaseFilters {
  page: number
  per_page: number
  search?: string
  jahr?: number
  fallgruppe?: string
  has_icd?: string
}

export function useCases(filters: CaseFilters, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: ['cases', filters],
    queryFn: () => {
      const params: Record<string, string | number> = {
        page: filters.page,
        per_page: filters.per_page,
      }
      if (filters.search) params.search = filters.search
      if (filters.jahr) params.jahr = filters.jahr
      if (filters.fallgruppe) params.fallgruppe = filters.fallgruppe
      if (filters.has_icd) params.has_icd = filters.has_icd
      return api.get<CaseListResponse>('/cases/', { params }).then(r => r.data)
    },
    enabled: options?.enabled ?? true,
  })
}

export function usePendingIcdCases(page: number, perPage: number, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: ['cases', 'pending-icd', { page, per_page: perPage }],
    queryFn: () => api.get<CaseListResponse>('/cases/pending-icd', {
      params: { page, per_page: perPage },
    }).then(r => r.data),
    enabled: options?.enabled ?? true,
  })
}

export function useCaseUpdate() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Record<string, unknown> }) =>
      api.put<Case>(`/cases/${id}`, data).then(r => r.data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['cases'] }),
  })
}

export function useKvnrUpdate() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, kvnr }: { id: number; kvnr: string | null }) =>
      api.put<Case>(`/cases/${id}/kvnr`, { kvnr }).then(r => r.data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['cases'] }),
  })
}

export function useIcdUpdate() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, icd }: { id: number; icd: string }) =>
      api.put<Case>(`/cases/${id}/icd`, { icd }).then(r => r.data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cases'] })
      queryClient.invalidateQueries({ queryKey: ['dashboard'] })
    },
  })
}
