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

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

// --- Types ---

export interface MonthlyReportData {
  month: string // YYYY-MM
  totalDistributions: number
  totalGrams: number
  uniqueMembers: number
  averagePerDistribution: number
  topStrains: { name: string; grams: number }[]
}

export interface MemberListReportData {
  totalMembers: number
  activeMembers: number
  suspendedMembers: number
  expelledMembers: number
  members: { id: string; name: string; status: string; joinedAt: string }[]
}

export interface RecallReportData {
  totalRecalls: number
  batches: {
    id: string
    strainName: string
    recalledAt: string
    reason: string
    gramsAffected: number
  }[]
}

// --- Query Hooks (preview data) ---

export function useMonthlyReportQuery(month?: string) {
  return useQuery({
    queryKey: ["reports", "monthly", month],
    queryFn: () =>
      apiClient<MonthlyReportData>("/reports/monthly", {
        params: { month: month || undefined },
      }),
    enabled: !!month,
  })
}

export function useMemberListReportQuery(status?: string) {
  return useQuery({
    queryKey: ["reports", "member-list", status],
    queryFn: () =>
      apiClient<MemberListReportData>("/reports/member-list", {
        params: { status: status || undefined },
      }),
  })
}

export function useRecallReportQuery(dateRange?: { from: string; to: string }) {
  return useQuery({
    queryKey: ["reports", "recalls", dateRange],
    queryFn: () =>
      apiClient<RecallReportData>("/reports/recalls", {
        params: {
          from: dateRange?.from,
          to: dateRange?.to,
        },
      }),
    enabled: !!dateRange,
  })
}

// --- Download Functions (imperative, not hooks) ---

export async function downloadMonthlyReportPdf(month: string) {
  const { blob, filename } = await apiDownload("/reports/monthly/pdf", {
    params: { month },
  })
  triggerDownload(blob, filename || `monthly-report-${month}.pdf`)
}

export async function downloadMonthlyReportCsv(month: string) {
  const { blob, filename } = await apiDownload("/reports/monthly/csv", {
    params: { month },
  })
  triggerDownload(blob, filename || `monthly-report-${month}.csv`)
}

export async function downloadMemberListPdf(status?: string) {
  const { blob, filename } = await apiDownload("/reports/member-list/pdf", {
    params: { status: status || undefined },
  })
  triggerDownload(blob, filename || "member-list.pdf")
}

export async function downloadRecallReportPdf(from: string, to: string) {
  const { blob, filename } = await apiDownload("/reports/recalls/pdf", {
    params: { from, to },
  })
  triggerDownload(blob, filename || `recall-report-${from}-${to}.pdf`)
}

// --- Helpers ---

function triggerDownload(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}
