import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
import { api, type ListRemittancesParams, type PaginatedResponse } from "@/lib/api";
import { useAppStore } from "@/store";
import type { Remittance } from "@/types";

/**
 * Lists remittances. Falls back to the in-memory zustand store when no
 * backend is configured; the fallback honors `offset` / `limit` and
 * returns the full list otherwise.
 */
export function useRemittances(params: ListRemittancesParams) {
  const fallback = useSyncExternalStore(
    (cb) => useAppStore.subscribe(cb),
    () => useAppStore.getState().remittances,
    () => useAppStore.getState().remittances
  );

  const q = useQuery<PaginatedResponse<Remittance>>({
    queryKey: ["remittances", params],
    queryFn: () => api.listRemittances<Remittance>(params),
    enabled: api.isConfigured,
  });

  if (!api.isConfigured) {
    const offset = params.offset ?? 0;
    const limit = params.limit ?? 100;
    const sliced = fallback.slice(offset, offset + limit);
    return {
      data: {
        items: sliced,
        total: fallback.length,
        returned: sliced.length,
        has_more: fallback.length > offset + limit,
      } satisfies PaginatedResponse<Remittance>,
      isLoading: false,
      isError: false,
      error: null,
      refetch: () => Promise.resolve(),
      dataUpdatedAt: 0,
    } as const;
  }
  return q;
}
