import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"

import type {
  AvailableBatch,
  Distribution,
  DistributionRecord,
  QuotaStatus,
} from "@/types/api"

import { apiClient } from "@/lib/api-client"

// --- Types ---

export interface DistributionsPage {
  content: DistributionRecord[]
  totalElements: number
  totalPages: number
  number: number
  size: number
}

export interface CreateDistributionRequest {
  memberId: string
  batchId: string
  amountGrams: number
}

// --- Query Hooks ---

export function useDistributionsQuery(params?: {
  page?: number
  size?: number
  memberId?: string
  from?: string
  to?: string
}) {
  return useQuery({
    queryKey: ["distributions", params],
    queryFn: () =>
      apiClient<DistributionsPage>("/distributions", {
        params: {
          page: params?.page,
          size: params?.size ?? 20,
          memberId: params?.memberId || undefined,
          from: params?.from || undefined,
          to: params?.to || undefined,
        },
      }),
  })
}

export function useRecentDistributionsQuery(limit = 5) {
  return useQuery({
    queryKey: ["distributions", "recent", limit],
    queryFn: () =>
      apiClient<Distribution[]>("/distributions/recent", {
        params: { limit },
      }),
  })
}

export function useQuotaQuery(memberId: string) {
  return useQuery({
    queryKey: ["members", memberId, "quota"],
    queryFn: () => apiClient<QuotaStatus>(`/members/${memberId}/quota`),
    enabled: !!memberId,
  })
}

export function useAvailableBatchesQuery() {
  return useQuery({
    queryKey: ["batches", "available"],
    queryFn: () => apiClient<AvailableBatch[]>("/batches/available"),
  })
}

// --- Mutation Hooks ---

export function useCreateDistributionMutation() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (data: CreateDistributionRequest) =>
      apiClient<DistributionRecord>("/distributions", {
        method: "POST",
        body: data,
      }),
    onSuccess: (_data, variables) => {
      // Invalidate distribution list + member quota
      queryClient.invalidateQueries({ queryKey: ["distributions"] })
      queryClient.invalidateQueries({
        queryKey: ["members", variables.memberId, "quota"],
      })
      queryClient.invalidateQueries({ queryKey: ["batches"] })
      queryClient.invalidateQueries({ queryKey: ["dashboard"] })
    },
  })
}
