import {
  normalizeInterests,
  resolveInterestOptionIds,
  type InterestDisplayItem,
  type InterestItem,
} from "@/lib/interests";
import {
  isRetiredOpportunityNationality,
  opportunityNationalityFrom,
} from "@/data/Constants";
import type { LearnServeFormValues } from "./learnServeFormTypes";

/** A localized master-choice, as the API embeds it on a record. */
import type { ChoiceDisplay } from "@/lib/choices";
import { displayFormValue } from "@/lib/choices";

/** The fields of a saved development opportunity this form reads back. */
export interface LearnServeOpportunityPayload {
  title_ar?: string | null;
  title_en?: string | null;
  description_ar?: string | null;
  description_en?: string | null;
  due_date?: string | null;
  registration_deadline_hours?: number | null;
  start_date?: string | null;
  end_date?: string | null;
  start_time?: string | null;
  end_time?: string | null;
  from_age?: number | string | null;
  to_age?: number | string | null;
  participants_needed?: number | string | null;
  price?: number | string | null;
  is_paid?: boolean | string | null;
  has_successful_payments?: boolean;
  has_active_payments?: boolean;
  link?: string | null;
  whatsapp_link?: string | null;
  location_url?: string | null;
  map_desc?: string | null;
  latitude?: number | string | null;
  longitude?: number | string | null;
  gender_display?: ChoiceDisplay | null;
  format_display?: ChoiceDisplay | null;
  learning_type_display?: ChoiceDisplay | null;
  certificate_type_display?: ChoiceDisplay | null;
  interest_display?: InterestDisplayItem[] | null;
  interests?: InterestItem[] | null;
  opportunity_sponsor_images?: Array<{
    organization?: { id?: unknown } | string | number | null;
  }> | null;
  opportunity_nationality?: string | null;
}

interface BuildInitialValuesArgs {
  /**
   * The record being edited; absent when publishing something new.
   *
   * Only the 27 fields this builder actually reads are declared. That is
   * narrower than `LearnServeOpportunityResource` on purpose — it makes a typo
   * in a field name a compile error, which an index signature or `any` would
   * both let through silently.
   */
  opportunityData?: LearnServeOpportunityPayload | null;
  selectedLanguage: string;
  /**
   * Whether the stored English text is genuinely different from the Arabic.
   *
   * An opportunity published without opening the English panel stores the
   * Arabic title in *both* columns, so these decide whether there is anything
   * worth loading into the English fields at all.
   */
  hasDistinctEnglishTitle: boolean;
  hasDistinctEnglishDescription: boolean;
  /**
   * The interest choices, needed to turn saved interest *names* back into the
   * option ids the checkbox grid is keyed by.
   */
  tagOptions: Array<{ id: string; label: string }>;
}

/**
 * Formik's starting values for the development-opportunity form.
 *
 * A pure function of the loaded record: the same payload always produces the
 * same values, which is what lets the form remount on a `key` change and land
 * in a predictable state.
 */
export function buildLearnServeInitialValues({
  opportunityData,
  selectedLanguage,
  tagOptions,
}: BuildInitialValuesArgs): LearnServeFormValues {
  return {
  paymentTermsLocked: opportunityData?.has_successful_payments === true || opportunityData?.has_active_payments === true,
  title_ar: opportunityData?.title_ar || "",

  title_en: opportunityData?.title_en || "",
  description_ar: opportunityData?.description_ar || "",
  description_en: "",
  dueDate: "",
  registrationDeadlineHours: opportunityData?.registration_deadline_hours != null ? String(opportunityData.registration_deadline_hours) : "",
  registrationDeadlineEnabled: opportunityData?.registration_deadline_hours != null,
  startDate: opportunityData?.start_date || "",
  endDate: opportunityData?.end_date || "",
  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?.slice(0, 5) || "",
  endTime: opportunityData?.end_time?.slice(0, 5) || "",
  learningType: displayFormValue(opportunityData?.learning_type_display),
  learnServeFormat: displayFormValue(opportunityData?.format_display),
  certificateType: displayFormValue(opportunityData?.certificate_type_display),
  location: opportunityData?.map_desc || "",
  location_url: opportunityData?.location_url || "",
  latitude: opportunityData?.latitude?.toString() || "",
  longitude: opportunityData?.longitude?.toString() || "",
  meetingLink: opportunityData?.link || "",
  whatsappLink: opportunityData?.whatsapp_link || "",
  gender: displayFormValue(opportunityData?.gender_display),
  /* Same reasoning as the volunteering form: «غير ناطق بالعربية» is no longer
     offered, so a record saved with it opens on an empty audience and the
     organizer picks again. Not defaulted to «كل الجنسيات» on their behalf —
     that would silently widen who the opportunity is open to. */
  opportunity_nationality: isRetiredOpportunityNationality(
    opportunityNationalityFrom(opportunityData ?? {})
  )
    ? ""
    : opportunityNationalityFrom(opportunityData ?? {}),
  is_paid: String(opportunityData?.is_paid === true),
  price:
    opportunityData?.price !== null && opportunityData?.price !== undefined
      ? String(opportunityData.price)
      : "",
  payout_bank_id: "",
  payout_bank_name: "",
  payout_bank_holder: "",
  payout_iban: "",
  payout_bank_edit: false,
  payout_bank_needed: false,
  opportunity_images: [],
  license_image: "",
  _interests: resolveInterestOptionIds(
    normalizeInterests(
      opportunityData?.interest_display,
      opportunityData?.interests
    ),
    tagOptions
  ),
  sponsors: opportunityData?.opportunity_sponsor_images?.length
    ? opportunityData.opportunity_sponsor_images.map(
        (sponsor: { organization?: { id?: unknown } | string | number | null }, index: number) => ({
          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,
  primary_language: selectedLanguage || "en",
  };
}
