"use client";

import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { billingKeys, queryKeys } from "@/lib/query-keys";
import { cleanParams, type QueryParams } from "@/hooks/use-resource";
import type {
  ApiResponse, ArrearsMeta, ArrearsRow, DashboardData, GridMeta, GridRow, Invoice, PaymentDetail, PaymentMethod, WaMeta,
} from "@/types";

/** Setelah transaksi uang, segarkan semua data penagihan & pelanggan. */
function useInvalidateBilling() {
  const qc = useQueryClient();
  return () => {
    qc.invalidateQueries({ queryKey: billingKeys.all });
    qc.invalidateQueries({ queryKey: queryKeys.customers });
  };
}

export function useBillingGrid(params: QueryParams) {
  const clean = cleanParams(params);
  return useQuery({
    queryKey: billingKeys.grid(clean),
    queryFn: async () => (await api.get<ApiResponse<GridRow[], GridMeta>>("/billing-grid", { params: clean })).data,
    placeholderData: keepPreviousData,
  });
}

export function useInvoice(id: number | null) {
  return useQuery({
    queryKey: billingKeys.invoice(id ?? 0),
    queryFn: async () => (await api.get<ApiResponse<Invoice, null>>(`/invoices/${id}`)).data.data,
    enabled: !!id,
  });
}

export function useGenerateInvoices() {
  const invalidate = useInvalidateBilling();
  return useMutation({
    mutationFn: async (period: string) =>
      (await api.post<ApiResponse<{ period: string; created: number; skipped: number }, null>>("/invoices/generate", { period })).data,
    onSuccess: invalidate,
  });
}

export function useCreateInvoice() {
  const invalidate = useInvalidateBilling();
  return useMutation({
    mutationFn: async (input: { customer_id: number; period: string; amount?: number | null }) =>
      (await api.post<ApiResponse<Invoice, null>>("/invoices", input)).data,
    onSuccess: invalidate,
  });
}

export interface PaymentInput {
  invoice_id: number;
  paid_at: string;
  amount: number;
  method: PaymentMethod;
  notes?: string | null;
  proof?: File | null;
}

export function useCreatePayment() {
  const invalidate = useInvalidateBilling();
  return useMutation({
    mutationFn: async (input: PaymentInput) => {
      const form = new FormData();
      form.append("invoice_id", String(input.invoice_id));
      form.append("paid_at", input.paid_at);
      form.append("amount", String(input.amount));
      form.append("method", input.method);
      if (input.notes) form.append("notes", input.notes);
      if (input.proof) form.append("proof", input.proof);
      return (await api.post<ApiResponse<PaymentDetail, WaMeta>>("/payments", form)).data;
    },
    onSuccess: invalidate,
  });
}

export function useDeletePayment() {
  const invalidate = useInvalidateBilling();
  return useMutation({
    mutationFn: async (id: number) => (await api.delete<ApiResponse<null, null>>(`/payments/${id}`)).data,
    onSuccess: invalidate,
  });
}

export function usePayment(id: number | string) {
  return useQuery({
    queryKey: billingKeys.payment(id),
    queryFn: async () => (await api.get<ApiResponse<PaymentDetail, WaMeta>>(`/payments/${id}`)).data,
  });
}

/**
 * Buka kuitansi PDF. File diambil lewat axios (agar cookie sesi + header Sanctum ikut),
 * lalu ditampilkan di tab baru. Tab dibuka lebih dulu supaya tidak diblokir popup blocker.
 */
export async function openReceipt(paymentId: number, paper: "a5" | "80mm" = "a5", download = false) {
  const win = download ? null : window.open("", "_blank");
  try {
    const res = await api.get<Blob>(`/payments/${paymentId}/receipt`, {
      params: { paper: paper === "80mm" ? "80mm" : undefined, download: download ? 1 : undefined },
      responseType: "blob",
    });
    const url = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
    if (win) {
      win.location.href = url;
    } else {
      const a = document.createElement("a");
      a.href = url;
      a.download = `kuitansi-${paymentId}.pdf`;
      a.click();
    }
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  } catch (err) {
    win?.close();
    throw err;
  }
}

export function useArrears(params: QueryParams) {
  const clean = cleanParams(params);
  return useQuery({
    queryKey: billingKeys.arrears(clean),
    queryFn: async () => (await api.get<ApiResponse<ArrearsRow[], ArrearsMeta>>("/arrears", { params: clean })).data,
    placeholderData: keepPreviousData,
  });
}

export function useDashboard(period: string) {
  return useQuery({
    queryKey: billingKeys.dashboard(period),
    queryFn: async () => (await api.get<ApiResponse<DashboardData, null>>("/dashboard", { params: { period } })).data.data,
    placeholderData: keepPreviousData,
  });
}
