"use client";

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

import {
  getAllPages,
  getParticipantsPayments,
} from "@/features/opportunities/services/payments";
import { getLearnServeRegistrations } from "@/features/opportunities/services/learnServe";
import {
  withRowId,
  type ParticipantPaymentRow,
} from "@/features/opportunities/participantPaymentRecord";
import type { RegistrationRow } from "@/features/opportunities/registrationRow";
import { getOwnPlatformFee } from "@/features/profile/services/platformFee";
import type { ApiResponse } from "@/lib/api/types";
import { parsePlatformFee } from "@/features/opportunities/platformFee";
import { useAuthStore } from "@/store/authStore";

/**
 * BE-125 — the organizer's «المشاركون والمدفوعات» table.
 *
 * Loads **every** row rather than paging: the design's totals row is a sum
 * over all participants and the search/date filters run over all of them,
 * and the endpoint offers neither (BE-123). Capacity keeps it to a request or
 * two.
 *
 * The payments resource carries no phone, photo or civil ID, which the
 * design shows, so the registrations list — which does — is loaded alongside
 * and joined on the registration id. Until it answers, rows render with
 * what the payments resource has; if it fails, the screen says so.
 *
 * A refund answers with the refreshed row, which is written into the cached
 * list rather than refetching it.
 */
export function useParticipantsPayments(opportunityId: string | undefined) {
  const userId = useAuthStore((s) => s.user?.id);
  const userType = useAuthStore((s) => s.user?.user_type);
  const queryKey = ["participants-payments", opportunityId];

  const paymentsQuery = useQuery({
    queryKey,
    queryFn: () =>
      getAllPages((params) =>
        getParticipantsPayments(opportunityId as string, params)
      ),
    enabled: Boolean(opportunityId),
  });

  const peopleQuery = useQuery({
    queryKey: ["participants-payments-people", opportunityId],
    /* `LearnServeRegistrationRecord` is the same flat row; read it through
       the shared `RegistrationRow` adapter type like the register list does. */
    queryFn: () =>
      getAllPages<RegistrationRow>(
        (params) =>
          getLearnServeRegistrations({
            opportunity_id: opportunityId as string,
            ...params,
          }) as unknown as Promise<ApiResponse<RegistrationRow[]>>
      ),
    enabled: Boolean(opportunityId),
  });

  const { data: feeRate } = useQuery({
    queryKey: ["account-platform-fee", userId, userType],
    queryFn: () => getOwnPlatformFee(userType),
    enabled: userId != null,
    retry: false,
  });
  const feePercent = parsePlatformFee(feeRate);

  const people = useMemo(() => {
    const byId = new Map<string, RegistrationRow>();
    (peopleQuery.data ?? []).forEach((row) => byId.set(String(row.id), row));
    return byId;
  }, [peopleQuery.data]);

  const rows = useMemo(
    () => (paymentsQuery.data ?? []).map(withRowId),
    [paymentsQuery.data]
  );

  return {
    rows: rows as ParticipantPaymentRow[], people, feePercent,
    isLoading: paymentsQuery.isLoading, isError: paymentsQuery.isError,
    retry: () => void paymentsQuery.refetch(),
    /* Without the people lookup the phone / civil ID columns are blank and
       search by them finds nobody — said out loud rather than shown as empty. */
    peopleFailed: peopleQuery.isError,
    retryPeople: () => void peopleQuery.refetch(),
    refundingIds: new Set<number>(), refundingAll: false,
  };
}
