import type { VolunteerOpportunityDetailRecord } from "@/features/opportunities/opportunityRecord";
import { normalizeInterests, resolveInterestOptionIds } from "@/lib/interests";
import {
  isRetiredOpportunityNationality,
  opportunityNationalityFrom,
} from "@/data/Constants";
import { requiresAttendanceLocation } from "@/features/opportunities/attendanceLocation";
import { toFormDateValue, type ScheduleMode } from "./OpportunityScheduleDates";
import { VolunteerFormValues } from "./volunteerFormTypes";
import { displayFormValue } from "@/lib/choices";

interface BuildVolunteerInitialValuesArgs {
  /** The record being edited; absent when publishing something new. */
  /*
   * `VolunteerOpportunityDetailRecord` — the shape
   * `GET /opportunities/{id}/details/` returns, which is what the edit form
   * loads. `Record<string, any>` accepted any object and let all 32 reads
   * below go unchecked, which is how the nullability and the `ar_num()`
   * string halves went unnoticed.
   */
  opportunityData?: VolunteerOpportunityDetailRecord | null;
  /**
   * Whether the stored English text is genuinely different from the Arabic.
   *
   * An opportunity published without opening the English panel stores the
   * Arabic text in *both* columns, so these decide whether there is anything
   * worth loading into the English fields at all.
   */
  hasDistinctEnglishTitle: boolean;
  hasDistinctEnglishDescription: boolean;
  /** The saved schedule, already normalized by the caller. */
  storedScheduleDates: string[];
  storedScheduleMode: ScheduleMode;
  /** Interest choices, to map saved interest names back to option ids. */
  tagOptions: Array<{ id: string; label: string }>;
  /** Present when editing; the public/private answer only applies then. */
  id?: string | null;
}

/**
 * Formik's starting values for the volunteering form.
 *
 * A pure function of the loaded record, which is what lets the form remount on
 * a `key` change and land in a predictable state.
 */
export function buildVolunteerInitialValues({
  opportunityData,
  storedScheduleDates,
  storedScheduleMode,
  tagOptions,
  id,
}: BuildVolunteerInitialValuesArgs): VolunteerFormValues {
  return {
  title_ar: opportunityData?.title_ar || "",

  title_en: "",
  dueDate: "",
  registrationDeadlineHours: opportunityData?.registration_deadline_hours != null ? String(opportunityData.registration_deadline_hours) : "",
  registrationDeadlineEnabled: opportunityData?.registration_deadline_hours != null,
  // Derived from the same array the calendar writes, and in the same local
  // midnight ISO form, so a record loaded for editing and one just picked
  // behave identically — see `toFormDateValue`.
  startDate: toFormDateValue(storedScheduleDates[0]),
  endDate: toFormDateValue(storedScheduleDates[storedScheduleDates.length - 1]),
  scheduleMode: storedScheduleMode,
  scheduleDates: storedScheduleDates,
  participantsNeeded: opportunityData?.participants_needed?.toString() || "",
  age: [
    opportunityData?.from_age ? Number(opportunityData.from_age) : null,
    opportunityData?.to_age ? Number(opportunityData.to_age) : null,
  ],
  startTime:
    opportunityData?.start_time?.split(":")?.slice(0, 2).join(":") || "",
  endTime: opportunityData?.end_time?.split(":")?.slice(0, 2).join(":") || "",
  volunteerHoursPerDay:
    opportunityData?.volunteer_hours_per_day?.toString() || "",
  gender: displayFormValue(opportunityData?.gender_display),
  location: opportunityData?.map_desc || "",
  /*
   * The API resource falls `location_url` back to `link` (the WhatsApp
   * number) when the column is empty, so an empty column arrives looking
   * like a maps link. Reading it back verbatim would copy the WhatsApp URL
   * into the location field on every edit, so the fallback is undone here.
   */
  locationUrl:
    opportunityData?.location_url &&
    opportunityData.location_url !== opportunityData?.link
      ? opportunityData.location_url
      : "",
  link: opportunityData?.link || "",
  description_ar: opportunityData?.description_ar || "",
  // Mirrored English loads as empty, not as the Arabic it copies — same
  // reasoning as `title_en` above.
  description_en: "",
  _interests: resolveInterestOptionIds(
    normalizeInterests(
      opportunityData?.interest_display,
      opportunityData?.interests
    ),
    tagOptions
  ),
  opportunity_images: [],
  license_image: "",
  /* BE-109 — a record saved with the retired audience opens with the field
     empty, so the organizer re-answers it rather than resubmitting a value
     the API now refuses. `isRetiredOpportunityNationality` says why. */
  opportunity_nationality: isRetiredOpportunityNationality(
    opportunityData?.opportunity_nationality
  )
    ? ""
    : opportunityNationalityFrom(opportunityData ?? {}),
  isPrivate: id
    ? opportunityData?.is_public === false
      ? "private"
      : "public"
    : "",
  latitude: opportunityData?.latitude?.toString() || "",
  longitude: opportunityData?.longitude?.toString() || "",
  /*
   * Through the shared helper rather than inline: it reads the flag off the
   * record and honours `ATTENDANCE_LOCATION_LIVE`, so the one place that
   * decides whether BE-101 is on stays one place. The field is live on the
   * API now (it was not when this form was written), and an older record
   * simply has it absent, which the helper reads as `false`.
   */
  requiresAttendanceLocation: requiresAttendanceLocation(opportunityData),
  sponsors: opportunityData?.opportunity_sponsor_images?.length
    ? opportunityData.opportunity_sponsor_images.map(
        /* No annotation: the element type comes from
       `opportunity_sponsor_images`, which is `OpportunitySponsorImage[]`. */
    (sponsor, index) => ({
          sponsorId:
            typeof sponsor.organization === "object" &&
            sponsor.organization !== null
              ? String(sponsor.organization.id)
              : String(sponsor.organization ?? ""),
          position: index + 1,
        })
      )
    : [{ sponsorId: "", position: 1 }],
  license_image_removed: false,
  volunteerCategory: opportunityData?.volunteer_category || "",
  beneficiariesCount:
    opportunityData?.beneficiaries_count != null
      ? String(opportunityData.beneficiaries_count)
      : "",
  };
}
