import { nationalityResidencyValueFrom, speaksArabicValueFrom } from "@/data/Constants";
import { type CombinedFormValues } from "./volunteerAccountTypes";
import type { ApiResponse } from "@/lib/api/types";
import type {
  AccountRecord,
  VolunteerProfileRecord,
} from "@/features/profile/accountRecords";
import { DEFAULT_DIAL_CODE } from "@/data/defaultCountry";

/**
 * The saved account and profile, flattened into one Formik object.
 *
 * Two records arrive from two endpoints and are asked for as one form, so this
 * is where the two are merged — and where every "the API sends an id, the select
 * matches a string" coercion happens. A numeric id left uncoerced leaves a
 * dropdown visibly unset; the same class of bug was found and fixed in
 * `learnServeInitialValues`.
 */
export function buildVolunteerAccountInitialValues(
  /* Both are the whole `ApiResponse` envelope, not the records — every read
     below goes through `?.data?.`, which is why the parameters are typed as the
     envelope rather than as `AccountRecord` / `VolunteerProfileRecord`. */
  accountData: ApiResponse<AccountRecord> | undefined,
  volunteerProfile: ApiResponse<VolunteerProfileRecord> | undefined
): CombinedFormValues {
  const initialValues: CombinedFormValues = {
    email: accountData?.data?.email || "",
    phone_number: accountData?.data?.phone_number || "",
    /* Kuwait by default when the account has no saved code, declared here
       rather than seeded by `CountryCodeSelect` from a mount effect. See
       `DEFAULT_DIAL_CODE`. */
    country_code: accountData?.data?.country_code || DEFAULT_DIAL_CODE,
    password: accountData?.data?.password || " ",
    first_name: accountData?.data?.first_name || "",
    last_name: accountData?.data?.last_name || "",
    documents: [],
    nickname: volunteerProfile?.data?.nickname ?? "",
    occupation: volunteerProfile?.data?.occupation ?? "",
    experience_field: volunteerProfile?.data?.experience ?? "",
    /* `ChoiceDisplay.id` is `number | null | undefined`, and the form field is
       `number[]` — the old `(interest: { id: string })` annotation claimed a
       string and was simply wrong about both. The null filter is a type guard
       so a `*_display` entry with no id cannot become `undefined` in the
       selected set and silently un-tick a checkbox. */
    _interests:
      volunteerProfile?.data?.interest_display
        ?.map((interest) => interest.id)
        .filter((id): id is number => typeof id === "number") ?? [],
    health_concerns: volunteerProfile?.data?.health_concerns === "yes" ? "yes"
      : volunteerProfile?.data?.health_concerns === "no" ? "no" : "",
    show_real_name: volunteerProfile?.data?.show_real_name ?? false,
    do_not_disturb: volunteerProfile?.data?.do_not_disturb ?? false,
    gender: volunteerProfile?.data?.gender_display?.id ?? "",
    nationality: nationalityResidencyValueFrom(
      volunteerProfile?.data?.nationality ?? accountData?.data?.nationality,
      volunteerProfile?.data?.residency_status ??
        accountData?.data?.residency_status
    ),

    speaks_arabic: speaksArabicValueFrom(
      volunteerProfile?.data?.speaks_arabic ?? accountData?.data?.speaks_arabic
    ),
    dob: volunteerProfile?.data?.dob ?? "",
    civil_id: volunteerProfile?.data?.civil_id ?? "",
    passport_number: volunteerProfile?.data?.passport_number ?? "",
    emergency_contact_name: accountData?.data?.emergency_contact_name ?? "",
    emergency_contact_phone: accountData?.data?.emergency_contact_phone ?? "",
    emergency_contact_country_code:
      accountData?.data?.emergency_contact_country_code || DEFAULT_DIAL_CODE,
    emergency_contact_civil_id:
      accountData?.data?.emergency_contact_civil_id ?? "",
    emergency_contact_relationship:
      accountData?.data?.emergency_contact_relationship_display?.id ?? "",
    /* `socialMediaList()` returns `[]` for an account with no links; the form
       needs one blank row to render an input against. */
    socialMedia:
      volunteerProfile?.data?.socialMedia &&
      volunteerProfile.data.socialMedia.length > 0
        ? volunteerProfile.data.socialMedia
        : [{ platform: "", link: "" }],
  };
  return initialValues;
}
