import type {
  LearnServeTimeSlotRecord,
  VolunteerOpportunityDetailRecord,
} from "@/features/opportunities/opportunityRecord";
import type { VolunteerOpportunityTeamRecord } from "@/features/opportunities/rolesAndTeamsRecord";
import type { VolunteerRegistrationRow } from "@/features/opportunities/volunteerRegistrationRecord";
import apiClient from "@/lib/api/client";
import type { ApiResponse, VolunteerRegistrationsDownload } from "@/lib/api/types";
import type { QueryParams } from "@/lib/api/types";
import type { TimeSlotPayload } from "@/features/opportunities/components/useTimeSlotSubmit";

// ─── Registrations ───────────────────────────────────────────────────────────

/**
 * `VolunteerOpportunityRegistrationController::createRegistration()`.
 *
 * Only the opportunity is required; `role_id` and `team_id` are `nullable`
 * and, when sent, must belong to *that* opportunity — a mismatch is a 400 with
 * "Role does not belong to opportunity.", not a validation error.
 *
 * `organization_id` is `['nullable', 'integer']` with **no `exists:` rule**,
 * which is why it is typed and sent as given rather than checked here; it is
 * the organization whose page the volunteer registered from.
 */
export interface RegisterForVolunteerOpportunityBody {
  opportunity_id: number | string;
  role_id?: number | string;
  team_id?: number | string;
  organization_id?: number | string;
  /** Resubmit after a 409 schedule conflict: cancel the clashing registration first. */
  cancel_conflicting?: boolean;
}

/**
 * The envelope's `data` on success (201).
 *
 * Not a bare Resource: the controller wraps the registration together with the
 * age figures it checked, so the caller can explain a refusal without asking
 * again. `meets_age_requirement` is hard-coded `true` on this branch — an
 * age mismatch returns a 400 instead, so the key is only ever `true` when it
 * is present at all.
 */
export interface VolunteerRegistrationResult {
  registration: Record<string, unknown>;
  assignment_id: number | null;
  /** `max(0, participants_needed - assigned)`. */
  remaining_slots: number;
  user_age: number;
  required_age_from: number;
  /** Null when the opportunity sets no upper bound. */
  required_age_to: number | null;
  meets_age_requirement: boolean;
}

export const registerForVolunteerOpportunity = (
  data: RegisterForVolunteerOpportunityBody
): Promise<ApiResponse<VolunteerRegistrationResult>> =>
  apiClient.post("/volunteer-opportunity-registrations/", data).then((r) => r.data);

export const unregisterFromVolunteerOpportunity = (id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/volunteer-opportunities/${id}/unregister/`).then((r) => r.data);

/**
 * Creator-only: stop accepting registrations before the due date is reached.
 *
 * All three of these answer with the **whole opportunity** in the detail shape
 * — the same `VolunteerOpportunityResource` that
 * `GET /opportunities/{id}/details/` returns — so a caller can refresh from
 * the reply instead of refetching.
 */
export const closeVolunteerOpportunityRegistration = (
  id: string
): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post(`/volunteer-opportunities/${id}/close-registration/`).then((r) => r.data);

/** Creator-only: reopen registration after closing it early. */
export const reopenVolunteerOpportunityRegistration = (
  id: string, data?: { participants_needed: number }
): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post(`/volunteer-opportunities/${id}/reopen-registration/`, data).then((r) => r.data);

/**
 * BE-108 — what the organizer's message reaches its recipients through.
 *
 * Every registrant gets an **in-app notification**; the email is sent on top of
 * it and is skipped for anyone with no address or with `do_not_disturb` set
 * (`RegistrationManagementService::sendEmail`). So `sent_count` is the number
 * of **emails**, which is at most the number of people messaged and routinely
 * fewer — it must not be reported as "sent to N volunteers".
 */
export interface OrganizerMessageResult {
  sent_count: number;
}

/**
 * Creator-only: message this opportunity's registrants.
 *
 * `POST /volunteer-opportunities/{id}/registrations/message/`. Either `all` or
 * a non-empty `registration_ids` is required — the API answers 400 when both
 * are absent rather than quietly messaging nobody. `status` narrows to one
 * approval state; omitted, every registration is included.
 *
 * The limits are the server's own (`max:255` / `max:10000`), mirrored in the
 * form so the organizer is told before sending rather than after.
 */
export const messageVolunteerRegistrants = ({
  opportunityId,
  subject,
  message,
  all = true,
  registrationIds,
  status,
}: {
  opportunityId: string;
  subject: string;
  message: string;
  all?: boolean;
  registrationIds?: number[];
  status?: string;
}): Promise<ApiResponse<OrganizerMessageResult>> =>
  apiClient
    .post(`/volunteer-opportunities/${opportunityId}/registrations/message/`, {
      subject,
      message,
      ...(all ? { all: true } : { registration_ids: registrationIds ?? [] }),
      ...(status ? { status } : {}),
    })
    .then((r) => r.data);

/**
 * The development-opportunity twin of `messageVolunteerRegistrants`:
 * `POST /learn-serve-opportunities/{id}/registrations/message/`, same body,
 * same rules, same `{ sent_count }` answer.
 */
export const messageLearnServeRegistrants = ({
  opportunityId,
  subject,
  message,
  all = true,
  registrationIds,
  status,
}: {
  opportunityId: string;
  subject: string;
  message: string;
  all?: boolean;
  registrationIds?: number[];
  status?: string;
}): Promise<ApiResponse<OrganizerMessageResult>> =>
  apiClient
    .post(`/learn-serve-opportunities/${opportunityId}/registrations/message/`, {
      subject,
      message,
      ...(all ? { all: true } : { registration_ids: registrationIds ?? [] }),
      ...(status ? { status } : {}),
    })
    .then((r) => r.data);

/** Creator-only: send a rejected opportunity back into the admin review queue. */
export const resubmitVolunteerOpportunity = (
  id: string
): Promise<ApiResponse<VolunteerOpportunityDetailRecord>> =>
  apiClient.post(`/volunteer-opportunities/${id}/resubmit/`).then((r) => r.data);

/**
 * Reassign a registration's team or role.
 *
 * The route carries no `{id}` — `VolunteerOpportunityRegistrationController::
 * updateAssignment` validates `registration` out of the *body*, alongside an
 * optional `role` and `team`. There is a separate `PATCH .../{id}/` on the
 * backend, but it is a different action and this is not it.
 */
export interface VolunteerAssignmentUpdate {
  registration: string;
  role?: string;
  team?: string;
}

/**
 * The reassigned registration, through `VolunteerOpportunityRegistrationResource`
 * — the same row the organizer's list renders, so the reply can be patched into
 * the list rather than triggering a refetch.
 *
 * It was `Record<string, unknown>`, which is worse than `unknown`: an index
 * signature satisfies every required-key check, so a caller could read any
 * field name off it and get `unknown` instead of an error. That is the same
 * hole that let the review-create body ship with the wrong id key.
 */
export const updateVolunteerRegistration = (
  data: VolunteerAssignmentUpdate
): Promise<ApiResponse<VolunteerRegistrationRow>> =>
  apiClient.patch(`/volunteer-opportunity-registrations/`, data).then((r) => r.data);

/**
 * Team and role filters go over the wire as `team_id[]` / `role_id[]`: PHP keeps only
 * the last value of a repeated plain key, so the bracket form is what lets several
 * selected roles all reach the backend. Built by hand rather than left to axios.
 */
export const getVolunteerRegistrations = ({
  opportunity_id,
  page = 1,
  limit = 10,
  teams,
  roles,
  search,
}: {
  opportunity_id?: string;
  page?: number;
  limit?: number;
  teams?: number[];
  roles?: number[];
  search?: string;
}) => {
  const params = new URLSearchParams();
  params.append("opportunity_id", String(opportunity_id ?? ""));
  params.append("page", String(page));
  params.append("limit", String(limit));
  teams?.forEach((team) => params.append("team_id[]", String(team)));
  roles?.forEach((role) => params.append("role_id[]", String(role)));
  if (search) params.append("search", search);

  return apiClient
    .get("/volunteer-opportunity-registrations/", { params })
    .then((r) => r.data);
};

export const downloadVolunteerRegistrations = ({
  opportunity_id,
  teams,
  roles,
  search,
  date,
}: {
  opportunity_id: string;
  teams?: number[];
  roles?: number[];
  search?: string;
  date?: string;
}): Promise<VolunteerRegistrationsDownload> => {
  const params = new URLSearchParams();
  params.append("opportunity_id", opportunity_id);
  params.append("download", "true");
  teams?.forEach((team) => params.append("team_id[]", String(team)));
  roles?.forEach((role) => params.append("role_id[]", String(role)));
  if (search) params.append("search", search);
  if (date) params.append("date", date);

  return apiClient
    .get<ApiResponse<VolunteerRegistrationsDownload>>(
      "/volunteer-opportunity-registrations/",
      { params }
    )
    .then((r) => r.data.data);
};

/**
 * `directRegister()` — the organizer adding volunteers itself.
 *
 * `user_ids` is `['required', 'array', 'min:1']`, so an empty array is a 422
 * rather than a no-op. Each id must exist.
 */
export interface DirectRegisterVolunteersBody {
  opportunity_id: number | string;
  /** At least one; each must be an existing user id. */
  user_ids: (number | string)[];
}

/**
 * Partial success is normal here: the endpoint loops over the ids and reports
 * each one, answering **201 when at least one succeeded and 400 when none
 * did** — so the status alone does not say what happened and the two counts
 * have to be read.
 */
export interface DirectRegisterResult {
  successful_registrations: Array<{
    user_id: number;
    /** `first_name last_name`, trimmed — empty string when both are null. */
    user_name: string;
    registration: Record<string, unknown>;
    assignment_id: number;
  }>;
  failed_registrations: Array<{ user_id: number; error: string }>;
  success_count: number;
  failed_count: number;
  remaining_slots: number;
}

export const directRegisterVolunteer = (
  data: DirectRegisterVolunteersBody
): Promise<ApiResponse<DirectRegisterResult>> =>
  apiClient.post("/volunteer-opportunity-registrations/direct-register/", data).then((r) => r.data);

/**
 * `directUnregister()` — which **rejects** rather than deletes: each matching
 * registration is set to `ApprovalStatus::REJECTED` and the volunteer is
 * notified.
 *
 * `user_ids` is *not* in the `validate()` call here — only `opportunity_id`
 * is. The ids are read with `$request->input('user_ids', [])`, a single
 * `user_id` is accepted as an alias, and an empty list is a 400 from the
 * controller rather than a 422 from the validator. Typed as required because
 * sending none is never useful.
 */
export interface DirectUnregisterVolunteersBody {
  opportunity_id: number | string;
  user_ids: (number | string)[];
  /**
   * BE-138 — without it, a volunteer with attendance or a certificate is
   * skipped and listed in `blocked`. The organizer's confirmation dialog is the
   * opt-in, so the screen sends it.
   */
  confirm?: boolean;
}

/** Both keys hold the same number; the endpoint emits both. */
export interface DirectUnregisterResult {
  rejected_count: number;
  removed_count: number;
  /** Skipped for their history when `confirm` was not sent. */
  blocked?: Array<{ user_id: number; registration_id: number }>;
}

export const directUnregisterVolunteer = (
  data: DirectUnregisterVolunteersBody
): Promise<ApiResponse<DirectUnregisterResult>> =>
  apiClient.post("/volunteer-opportunity-registrations/direct-unregister/", data).then((r) => r.data);

// ─── Teams ───────────────────────────────────────────────────────────────────

export const getTeams = (
  params?: QueryParams
): Promise<ApiResponse<VolunteerOpportunityTeamRecord[]>> =>
  apiClient.get("/volunteer-opportunity-teams/", { params }).then((r) => r.data);

/**
 * `VolunteerOpportunityTeamController::store()` — both names `required`,
 * `max:255`, same as roles. 201 with the created team.
 */
export interface CreateVolunteerTeamBody {
  opportunity_id: number | string;
  /** `max:255`. */
  team_name_en: string;
  /** `max:255`. */
  team_name_ar: string;
}

/** `update()` takes the two names as `sometimes`, and no opportunity id. */
export type UpdateVolunteerTeamBody = Partial<
  Omit<CreateVolunteerTeamBody, "opportunity_id">
>;

export const createTeam = (
  data: CreateVolunteerTeamBody
): Promise<ApiResponse<VolunteerOpportunityTeamRecord>> =>
  apiClient.post("/volunteer-opportunity-teams/", data).then((r) => r.data);

export const updateTeam = ({
  id,
  data,
}: {
  id: string;
  data: UpdateVolunteerTeamBody;
}): Promise<ApiResponse<VolunteerOpportunityTeamRecord>> =>
  apiClient.patch(`/volunteer-opportunity-teams/${id}/`, data).then((r) => r.data);

export const deleteTeam = (id: string): Promise<ApiResponse<null>> =>
  apiClient.delete(`/volunteer-opportunity-teams/${id}/`).then((r) => r.data);

export const getTeamById = (
  id: string
): Promise<ApiResponse<VolunteerOpportunityTeamRecord>> =>
  apiClient.get(`/volunteer-opportunity-teams/${id}/`).then((r) => r.data);

// ─── Time Slots ──────────────────────────────────────────────────────────────

/* All three read the same endpoint and the same resource. Note the row shape:
   `LearnServeTimeSlotResource` keys the parent as **`opportunity`** — a bare
   integer — not `opportunity_id` like the roles and teams resources do. */
export const getOpportunityTimeSlots = ({
  opportunity_id,
  page,
  limit,
}: {
  opportunity_id: string;
  page?: number;
  limit?: number;
}): Promise<ApiResponse<TimeSlotListPayload>> =>
  apiClient.get(`/time-slots/?opportunity_id=${opportunity_id}&page=${page}&limit=${limit}`).then((r) => r.data);

/**
 * `LearnServeTimeSlotController::index` answers `data: { items, remaining_participants }`
 * (only slots that still have room), not a bare array.
 */
export interface TimeSlotListPayload {
  items: LearnServeTimeSlotRecord[];
  remaining_participants: number;
}

/** The slots of a `GET /time-slots/` reply, tolerating an older bare-array body. */
export function timeSlotItems(
  data: TimeSlotListPayload | LearnServeTimeSlotRecord[] | null | undefined
): LearnServeTimeSlotRecord[] {
  if (Array.isArray(data)) return data;
  return Array.isArray(data?.items) ? data.items : [];
}

export const getTimeSlots = (
  opportunity_id: string | number
): Promise<ApiResponse<TimeSlotListPayload>> =>
  apiClient.get(`/time-slots/?opportunity_id=${opportunity_id}`).then((r) => r.data);

export const getConsultationTimeSlots = (
  opportunity_id: string | number
): Promise<ApiResponse<TimeSlotListPayload>> =>
  apiClient.get(`/time-slots/?opportunity_id=${opportunity_id}`).then((r) => r.data);

/* Typed per endpoint rather than as a loose record: `LearnServeTimeSlotController::store()` requires
   `opportunity_id` and the frontend was sending `opportunity`, so every create
   was a 422. Naming the shape is what keeps that from recurring. */
export const createTimeSlot = (
  data: TimeSlotPayload
): Promise<ApiResponse<LearnServeTimeSlotRecord>> =>
  apiClient.post("/time-slots/", data).then((r) => r.data);

export const updateTimeSlot = ({
  id,
  opportunity_id,
  data,
}: {
  id: string;
  /* A query-string argument on this route, not part of the body. */
  opportunity_id: string;
  data: TimeSlotPayload;
}): Promise<ApiResponse<LearnServeTimeSlotRecord>> =>
  apiClient.patch(`/time-slots/${id}/?opportunity_id=${opportunity_id}`, data).then((r) => r.data);

export const deleteTimeSlot = ({ id, opportunity_id }: { id: string; opportunity_id: string }): Promise<ApiResponse<null>> =>
  apiClient.delete(`/time-slots/${id}/?opportunity_id=${opportunity_id}`).then((r) => r.data);

export const deleteAllTimeSlots = (opportunity_id: number): Promise<ApiResponse<null>> =>
  apiClient.delete(`/delete-time-slots/${opportunity_id}/`).then((r) => r.data);
