import moment from "moment";
import { parseKuwaitInstant } from "@/features/shared/clientReviewPolicy";
import type { VolunteerOpportunityRoleRecord } from "@/features/opportunities/rolesAndTeamsRecord";
import type { VolunteerRegistrationRow } from "@/features/opportunities/volunteerRegistrationRecord";

/**
 * A registrations-table row.
 *
 * Was `export type UntypedRow = any`, with a note claiming that narrowing it
 * "would mean transcribing six resources and reconciling them". That was
 * wrong: every row this table renders comes from
 * `VolunteerOpportunityRegistrationResource`, one resource of twenty-four
 * keys, now transcribed as `VolunteerRegistrationRow`. The alias survives
 * under its old name because fifteen call sites import it, and the name is
 * kept honest by the type behind it rather than by a suppression.
 *
 * `AttendanceRow` below remains the *narrow* view — the three fields the date
 * and attendance rules read — so those helpers still accept a download row
 * that carries no `volunteer_uuid`.
 */
export type UntypedRow = VolunteerRegistrationRow;

/**
 * The part of a row the date and attendance rules below actually read.
 *
 * Narrow where it can be: these five functions were each annotated `any` while
 * between them they touch exactly three fields. `registration_date` is an ISO
 * timestamp and not just a day — `canMarkAttendanceForDate` compares its *time*
 * against the session end, which is the whole point of the same-day branch.
 */
export interface AttendanceRow {
  /** `string | null`, not `string | undefined`: the resource emits
      `optional($this->registration_date)?->toIso8601String()`, which is
      `null` for a row with no timestamp — a download row omits the key
      entirely, hence both. */
  registration_date?: string | null;
  /** `Y-m-d` strings — days this volunteer is already marked present for. */
  date_wise_attended?: string[];
  /** The id the bulk-attendance endpoint takes. `null` when the volunteer has
      no profile (so no uuid), and absent on a download row — hence both. */
  volunteer_uuid?: string | null;
}

/** Carried over from the opportunity detail page that linked here. */
export interface VolunteerListState {
  id?: string;
  opportunity_status?: string;
  manual_tracking?: boolean;
  disableDeleteAfterPeriod?: boolean;
  start_date?: string;
  start_at?: string | null;
  end_at?: string | null;
  registration_closes_at?: string | null;
  end_date?: string;
  start_time?: string;
  end_time?: string;
  /**
   * Per-day schedule, for opportunities on separate days. The hours field
   * reads it to cap each day at that day's own length (see `attendanceHours.ts`).
   */
  time_slots?: {
    date?: string | null;
    start_time?: string | null;
    end_time?: string | null;
    hours?: number | null;
  }[];
  participants_needed?: number;
  // Check-in window fields, forwarded verbatim so this screen can render the
  // countdown and lock the controls without refetching the opportunity.
  requires_check_in?: boolean;
  qr_attendance_enabled?: boolean;
  manual_attendance_enabled?: boolean;
  preparation_valid_until?: string | null;
  preparation_valid_until_at?: string | null;
  is_preparation_window_closed?: boolean;
  preparation_reopened_until?: string | null;
  /*
   * BE-69 — this screen is reachable by two kinds of viewer now: the organizer,
   * and a volunteer granted «إذن تحضير». Both manage attendance; only the
   * organizer hands the permission out, so the two are carried separately
   * rather than collapsed into one "can manage" flag.
   */
  is_creator?: boolean;
  can_manage_attendance?: boolean;
  /** The opportunity's review state; see `awaitsApproval`. */
  approval_status?: string | null;
}

/**
 * PDF p.4 rule 1: an opportunity the administration has not approved takes no
 * participants. Backend `b6ed21c` answers 422 `opportunity_not_approved` to a
 * manual add, a self-scan or a manual check-in on a pending or rejected
 * volunteering opportunity (BE-258), so those controls are not offered there.
 * An absent status (older payload) is not treated as a refusal.
 */
export function awaitsApproval(approvalStatus: string | null | undefined): boolean {
  return approvalStatus === "pending" || approvalStatus === "rejected";
}

/**
 * Hours and undo act on an *attendance record*, not a registration, so they
 * need that record's id.
 *
 * BE-67.2 landed: `GET /volunteer-opportunity-registrations/` now returns an
 * `attendances[]` array carrying `{ id, attended_date, total_hours,
 * checked_in_at, max_hours, … }` per attended date, so both actions survive a
 * page refresh. The session-memory shapes below are kept because a manual
 * check-in answers with its own record before the list refetches, and because
 * `date_wise_attended` is still the array the attendance checkbox reads.
 */
export interface AttendanceRecordRef {
  id: string | number;
  total_hours?: number | null;
  /** When the attendance was recorded — scan or manual. */
  checked_in_at?: string | null;
  /** BE-91 — the day's cap, once sent. */
  max_hours?: number | null;
  /** BE-91 — set once the organizer corrected the hours; see `AttendanceEntry`. */
  hours_set_manually_at?: string | null;
}

/** The attendance-carrying fields a registration row might expose. */
export interface AttendanceBearingRow {
  attendance_id?: string | number | null;
  attendance_date?: string | null;
  total_hours?: number | null;
  attendance?: AttendanceEntry | null;
  attendances?: AttendanceEntry[] | null;
  date_wise_attendance?: AttendanceEntry[] | null;
}

export interface AttendanceEntry {
  id?: string | number | null;
  /** BE-67.2 spells it `attended_date`; our own check-in results use the others. */
  attended_date?: string | null;
  attendance_date?: string | null;
  date?: string | null;
  total_hours?: number | null;
  checked_in_at?: string | null;
  /** BE-91 — sent since 2026-10-03; still derived locally when absent. */
  max_hours?: number | null;
  /** The departure scan; null while it is still awaited. */
  checked_out_at?: string | null;
  /** `qr_self` (the volunteer's own scan), `qr` or `manual`. */
  recorded_via?: string | null;
  total_minutes?: number | null;
  /**
   * BE-91 — when the organizer corrected this row's hours by hand.
   *
   * Set makes the row **organizer-owned**: the number here is the
   * organizer's decision, even when it is zero.
   */
  hours_set_manually_at?: string | null;
  /**
   * The server's next scan for that day; null once the day's scan window
   * (session end + grace) has closed — `MissingCheckOut::isMissing`'s moment.
   */
  next_action?: string | null;
}

/** Everything a record ref keeps from an entry. */
const toRecordRef = (
  entry: AttendanceEntry & { id: string | number }
): AttendanceRecordRef => ({
  id: entry.id,
  total_hours: entry.total_hours ?? null,
  checked_in_at: entry.checked_in_at ?? null,
  max_hours: entry.max_hours ?? null,
  hours_set_manually_at: entry.hours_set_manually_at ?? null,
});

/** One volunteer's outcome from a fanned-out manual check-in. */
export interface ManualAttendanceResult {
  volunteerUuid: string;
  record: AttendanceEntry | null;
}

export interface Team {
  id: string;
  team_name_en: string;
  team_name_ar: string;
  [key: string]: string | number;
}

/**
 * One volunteer-opportunity role.
 *
 * `VolunteerOpportunityRoleRecord` — the transcription of
 * `VolunteerOpportunityRoleResource` — rather than the local shape, which
 * existed twice (here and in `VolunteerFilterModal`) and was wrong in two ways
 * that an index signature was hiding: `id` is a **number**, and
 * `[key: string]: string | number` admitted any key at all, so the three
 * `rolesData.data as Role[]` casts that fed it could never be checked. The
 * role's `role_name_*` and `instructions_*` columns are nullable too.
 */
export type Role = VolunteerOpportunityRoleRecord;

export interface SelectOption {
  label: string;
  value: string;
}

export function readAttendanceRecord(
  row: AttendanceBearingRow | null | undefined,
  apiDate: string
): AttendanceRecordRef | null {
  // Preferred shape: a per-date list of full attendance records.
  const perDate = row?.date_wise_attendance ?? row?.attendances;
  if (Array.isArray(perDate)) {
    const match = perDate.find(
      (entry) =>
        entry?.attended_date === apiDate ||
        entry?.attendance_date === apiDate ||
        entry?.date === apiDate
    );
    if (match?.id != null) {
      return toRecordRef({ ...match, id: match.id });
    }
  }

  // Single-record shapes, only trustworthy when they name the same date.
  const single = row?.attendance;
  if (
    single?.id != null &&
    (single.attended_date ?? single.attendance_date ?? single.date) === apiDate
  ) {
    return toRecordRef({ ...single, id: single.id });
  }
  if (row?.attendance_id != null && row?.attendance_date === apiDate) {
    return { id: row.attendance_id, total_hours: row.total_hours ?? null };
  }

  return null;
}

/** API attendance days are Kuwait calendar dates, independent of browser timezone. */
export const toApiDate = (value: string): string => parseKuwaitInstant(value)?.format("YYYY-MM-DD") ?? "";

export const atMidnight = (value: string | Date): Date => {
  const date = value instanceof Date ? moment(value).utcOffset(180) : parseKuwaitInstant(value);
  return date?.clone().startOf("day").toDate() ?? new Date(NaN);
};

/** Whether this volunteer may be marked present on `date`. */
export function canMarkAttendanceForDate(
  rowData: AttendanceRow | null | undefined,
  date: string,
  opportunity_end_time: string | undefined
): boolean {
  if (!rowData?.registration_date || !date || !opportunity_end_time) {
    return false;
  }

  const registeredAt = parseKuwaitInstant(rowData.registration_date);
  const registrationDay = toApiDate(rowData.registration_date);
  const selectedDay = toApiDate(date);
  if (!registeredAt || !selectedDay || !registrationDay) return false;
  if (selectedDay < registrationDay) return false;
  if (selectedDay > registrationDay) return true;
  const sessionEnd = parseKuwaitInstant(`${selectedDay}T${opportunity_end_time}`);
  return sessionEnd !== null && registeredAt.isSameOrBefore(sessionEnd);
}

/** A volunteer's first eligible day is the later of start date / signup date. */
export function isDateValidForVolunteer(
  volunteer: AttendanceRow | null | undefined,
  date: string,
  opportunity_start_date: string | undefined
): boolean {
  if (!date || !volunteer?.registration_date || !opportunity_start_date) {
    return true;
  }
  const earliestValidDate =
    atMidnight(volunteer.registration_date) > atMidnight(opportunity_start_date)
      ? atMidnight(volunteer.registration_date)
      : atMidnight(opportunity_start_date);
  return atMidnight(date) >= earliestValidDate;
}

export function selectableAttendanceUuids(
  rows: AttendanceRow[],
  date: string,
  opportunity_start_date: string | undefined,
  opportunity_end_time: string | undefined
): string[] {
  const formatted = toApiDate(date);
  return rows
    .filter((volunteer) => {
      const alreadyAttended = (volunteer.date_wise_attended || []).includes(
        formatted
      );
      return (
        !alreadyAttended &&
        isDateValidForVolunteer(volunteer, date, opportunity_start_date) &&
        canMarkAttendanceForDate(volunteer, date, opportunity_end_time)
      );
    })
    .map((volunteer) => volunteer.volunteer_uuid)
    /* A download row carries no `volunteer_uuid`; the predicate is a type guard
       rather than a bare `Boolean` so the return type stays `string[]`. */
    .filter((uuid): uuid is string => Boolean(uuid));
}

/**
 * The attendance selection to submit, given the state of the header checkbox.
 *
 * Derived rather than accumulated. While "select all" is in force the answer
 * for *every loaded row* is `selectableAttendanceUuids`, so a page that merges
 * later is included by construction — there is nothing to extend, and nothing
 * can be missed by an extension step that ran with the wrong arguments.
 *
 * That last clause is not hypothetical: the callback this replaces passed
 * `opportunity_end_date` where `opportunity_end_time` belongs, so
 * `canMarkAttendanceForDate` split `"2026-10-05"` on `":"`, got
 * `endHours = 2026, endMinutes = NaN`, and refused every volunteer who had
 * registered **on the selected day**. The header toggle passed the real end
 * time, so the two disagreed about the same rows.
 *
 * `manualTracking` gates it because the selection only exists on a manually
 * tracked opportunity; with QR scanning there is nothing to tick.
 *
 * Tested in `tests/attendanceSelection.test.ts`, including the paging and
 * date-change cases.
 */
export function effectiveAttendanceSelection({
  selectAllMode,
  manualTracking,
  rows,
  date,
  opportunity_start_date,
  opportunity_end_time,
  explicitSelection,
}: {
  selectAllMode: boolean;
  manualTracking: boolean;
  rows: AttendanceRow[];
  date: string;
  opportunity_start_date: string | undefined;
  opportunity_end_time: string | undefined;
  /** What the reader ticked by hand, used whenever the mode is off. */
  explicitSelection: string[];
}): string[] {
  if (!selectAllMode || !manualTracking) return explicitSelection;
  return selectableAttendanceUuids(
    rows,
    date,
    opportunity_start_date,
    opportunity_end_time
  );
}

/*
 * Both of these used to be written out here, and this copy read only
 * `rowData.created_at` where the other two copies also fell back to
 * `registration_date`. On a payload that sends the second and not the first,
 * this list **hid** a minor's guardian details while the development list showed
 * them — the organizer needs those either way. One implementation now, with the
 * fallback, tested in `tests/registrationEmergencyContact.test.ts`.
 */
export {
  calculateAgeAtRegistration,
  shouldShowEmergencyContact,
} from "@/features/opportunities/registrationEmergencyContact";

/**
 * Registrations can't be deleted once the volunteer's own first session has
 * begun — which may be later than the opportunity start if they signed up
 * after that day's session ended.
 */
export function hasVolunteerParticipationStarted(
  rowData: AttendanceRow | null | undefined,
  opportunity_start_date: string | undefined,
  opportunity_start_time: string | undefined,
  opportunity_end_time: string | undefined
): boolean {
  if (!rowData?.registration_date || !opportunity_start_date || !opportunity_start_time) {
    return false;
  }

  const registrationDateTime = new Date(rowData.registration_date);
  const opportunityStartDate = atMidnight(opportunity_start_date);
  const registrationDate = atMidnight(rowData.registration_date);

  const [endHours, endMinutes] = (opportunity_end_time || "23:59:59")
    .split(":")
    .map(Number);
  const registrationDateEventEnd = new Date(registrationDate);
  registrationDateEventEnd.setHours(endHours, endMinutes, 0, 0);

  let volunteerFirstDay: Date;
  if (registrationDate < opportunityStartDate) {
    volunteerFirstDay = new Date(opportunityStartDate);
  } else if (registrationDateTime > registrationDateEventEnd) {
    volunteerFirstDay = new Date(registrationDate);
    volunteerFirstDay.setDate(volunteerFirstDay.getDate() + 1);
  } else {
    volunteerFirstDay = new Date(registrationDate);
  }
  volunteerFirstDay.setHours(0, 0, 0, 0);

  const [startHours, startMinutes] = (opportunity_start_time || "00:00:00")
    .split(":")
    .map(Number);
  const volunteerParticipationStart = new Date(volunteerFirstDay);
  volunteerParticipationStart.setHours(startHours, startMinutes, 0, 0);

  return new Date() >= volunteerParticipationStart;
}

/*
 * `ProfileLinkTarget` and `goToProfile` used to live here.
 *
 * Both are gone: every name and avatar that linked to a profile now renders
 * `components/shared/ProfileLink`, which derives its href from the one rule in
 * `lib/profilePath.ts`. Being a `router.push` rather than a link, the old
 * helper was unreachable by keyboard at all five call sites.
 */


/** Today's Kuwait calendar date, the calendar attendance days use. */
export const kuwaitToday = (now: Date = new Date()): string =>
  moment(now).utcOffset(180).format("YYYY-MM-DD");

/**
 * Days on which this volunteer checked in but never checked out, so their
 * hours are still 0:00 (client answers p.6, additional note «لم يسجل خروج»).
 * Mirrors the backend's `VolunteerDailyCheckInOut::isAwaitingCheckOut()`: an
 * arrival by the volunteer's own scan (`qr_self`; a payload without the field
 * is not excluded) with no departure, no hand-set hours and 0 minutes. Only
 * days whose scan window closed count: the server's `next_action: null` when the
 * payload carries it (it is authoritative, so a payload fetched before the window
 * closed shows the tag only after the next fetch), or, for a payload without the
 * field, a day before today.
 */
export function missedCheckOutDays(
  row: AttendanceBearingRow | null | undefined,
  today: string = kuwaitToday()
): string[] {
  const entries = row?.attendances ?? row?.date_wise_attendance ?? [];
  if (!Array.isArray(entries)) return [];
  return entries
    .filter((entry) => {
      const day = entry?.attended_date ?? entry?.attendance_date ?? entry?.date;
      // The server's window verdict is authoritative when it is sent (S-VOL-5): the scan-out
      // window runs to 2 h after the session ends, so a session ending at 23:00 can still be
      // scanned out until 01:00 — a "day before today" test would already call it missed.
      // Only a payload without the field falls back to the calendar day.
      const windowClosed = entry != null && "next_action" in entry ? entry.next_action == null : !!day && day < today;
      return (
        !!day && windowClosed &&
        (entry.recorded_via == null || entry.recorded_via === "qr_self") &&
        !!entry.checked_in_at && !entry.checked_out_at &&
        !entry.hours_set_manually_at &&
        Number(entry.total_minutes ?? Math.round(Number(entry.total_hours ?? 0) * 60)) === 0
      );
    })
    .map((entry) => String(entry.attended_date ?? entry.attendance_date ?? entry.date));
}

/**
 * The row after an hours correction (S-VOL-4). `PATCH …/hours/` answers with
 * the attendance resource; merging its minutes and `hours_set_manually_at`
 * into the matching day is what clears the «لم يسجل خروج» tag and the local
 * alert count at once, as the X1 note asks, instead of after a reload.
 */
export function withCorrectedAttendance<T extends AttendanceBearingRow>(
  row: T,
  attendanceId: string | number,
  saved: Pick<AttendanceEntry, "total_hours" | "total_minutes" | "hours_set_manually_at">
): T {
  const patchList = (entries: AttendanceEntry[] | null | undefined) =>
    Array.isArray(entries)
      ? entries.map((entry) =>
          entry?.id != null && String(entry.id) === String(attendanceId)
            ? {
                ...entry,
                total_hours: saved.total_hours ?? entry.total_hours,
                total_minutes: saved.total_minutes ?? (saved.total_hours != null ? Math.round(Number(saved.total_hours) * 60) : entry.total_minutes),
                hours_set_manually_at: saved.hours_set_manually_at ?? new Date().toISOString(),
              }
            : entry
        )
      : entries;
  return { ...row, attendances: patchList(row.attendances), date_wise_attendance: patchList(row.date_wise_attendance) };
}

/**
 * The row after an attendance was undone (`PATCH …/undo/`): the entry is gone, so a QR
 * arrival that had no departure stops counting as «لم يسجل خروج» at once, not after a reload.
 */
export function withoutAttendance<T extends AttendanceBearingRow>(row: T, attendanceId: string | number): T {
  const drop = (entries: AttendanceEntry[] | null | undefined) =>
    Array.isArray(entries) ? entries.filter((entry) => !(entry?.id != null && String(entry.id) === String(attendanceId))) : entries;
  return { ...row, attendances: drop(row.attendances), date_wise_attendance: drop(row.date_wise_attendance) };
}

/** How many volunteers have at least one such day — the organizer's alert count. */
export function countMissedCheckOuts(
  rows: Array<AttendanceBearingRow | null | undefined>,
  today: string = kuwaitToday()
): number {
  return rows.filter((row) => missedCheckOutDays(row, today).length > 0).length;
}

/** The list `meta` of backend `bf3140b` (X1): the whole opportunity's count and the client's sentence. */
export interface MissedCheckOutMeta {
  missing_check_out_count?: number | null;
  missing_check_out_note_en?: string | null;
  missing_check_out_note_ar?: string | null;
}

/**
 * The organizer's alert. With every row on screen the local count wins — it
 * follows an hours fix at once, while `meta` waits for the next page fetch.
 * With only part of the list loaded (paging, a search, a role filter) only the
 * server knows the total, so its count and note are used.
 */
export function missedCheckOutAlert(
  rows: Array<AttendanceBearingRow | null | undefined>,
  meta: MissedCheckOutMeta | null | undefined,
  listComplete: boolean,
  language: string,
  today: string = kuwaitToday()
): { count: number; note: string | null } {
  const serverCount = meta?.missing_check_out_count;
  if (listComplete || typeof serverCount !== "number") return { count: countMissedCheckOuts(rows, today), note: null };
  const note = (language === "ar" ? meta?.missing_check_out_note_ar : meta?.missing_check_out_note_en) || null;
  return { count: serverCount, note: serverCount > 0 ? note : null };
}
