"use client";

import { useQuery } from "@tanstack/react-query";
import { getDropdownChoicesRequest } from "@/features/auth/services/authApi";
import { includeHeldGeneralTag, type InterestItem } from "@/lib/interests";
import type { PublishPermissions } from "@/lib/publishPermissions";
import {
  choiceFormValue,
  choiceLabel,
  toChoiceTagOptions,
  type ChoiceItem,
} from "@/lib/choices";

/**
 * Master-choice labels the form has to recognise by *name* rather than id.
 *
 * The backend mints these ids per environment, so the only stable handle is the
 * label — which is why they are matched in both languages.
 */
const LABELS = {
  online: { en: "ONLINE", ar: "عن بعد" },
  inPerson: { en: "IN PERSON", ar: "حضوري" },
  internship: { en: "Internship", ar: "تدريب عملي" },
  course: { en: "Course", ar: "دورة" },
  forsaCertificate: { en: "Forsa Certificate", ar: "شهادة فرصة" },
} as const;

const labelFor = (key: keyof typeof LABELS, language: string): string =>
  LABELS[key][language === "ar" ? "ar" : "en"];

const findOptionValue = (
  options: Array<{ label: string; value: string }>,
  key: keyof typeof LABELS,
  language: string
): string | undefined =>
  options.find((option) => option.label === labelFor(key, language))?.value;

/*
 * `master_choices` rows come from the shared definition in `lib/choices`. The
 * local copy this replaces declared `id: string`, which the `as Choice[]` casts
 * below then asserted onto a payload whose ids are integers — so every option
 * built here was typed `value: string` while holding a number at runtime. That
 * mismatch is why the audience fields downstream had to be re-typed.
 */
type Choice = ChoiceItem;

/**
 * `String(item.id)`, not the raw id — this is a bug fix, not a style choice.
 *
 * `LearnServeFormValues` declares every id field as a string and
 * `learnServeInitialValues` fills them with `...id?.toString()`, so on *edit*
 * `values.learningType` holds `"3"`. The raw numeric id this used to return
 * made `values.learningType === internshipTypeId` compare `"3" === 3`, which is
 * always false, so on any edit that did not re-pick the dropdown:
 *   - `grantsCertificate` was false and `certificate_type_id` was submitted
 *     empty, silently stripping the certificate from a course or internship;
 *   - the internship guard on `isPaidOpportunity` never fired;
 *   - `values.learnServeFormat === onlineFormatId` was false, so an online
 *     opportunity was submitted with `map_desc` instead of `link` and lost its
 *     meeting link.
 * The payload is `FormData` throughout, and `append()` stringifies, so the
 * submitted bytes are unchanged for the create path that already worked.
 * Covered by `tests/learnServeChoiceIds.test.ts`.
 */
const toOption = (item: Choice, language: string) => ({
  label: choiceLabel(item, language),
  value: choiceFormValue(item),
});

/** Display order for the learning-type dropdown, regardless of API order. */
const LEARNING_TYPE_ORDER = [
  "Class/Workshop",
  "Course",
  "Consultation",
  "Internship",
];

/**
 * The five dropdowns behind the development-opportunity form, plus the handful
 * of ids the form's rules compare against.
 *
 * Gathered here because they are one concern — turn `master_choices` into
 * `{label, value}` in the current language — repeated five times, and because
 * the id lookups (`onlineFormatId`, `courseTypeId`, …) are what the validation
 * schema and half the conditional fields key off. The component only needs the
 * result.
 */
/** The whole dropdown layer, passed down as one prop rather than ten. */
export type LearnServeOptions = ReturnType<typeof useLearnServeOptions>;

export function useLearnServeOptions(
  selectedLanguage: string,
  publishPermissions: PublishPermissions,
  heldInterests?: InterestItem[] | null
) {
  const { data: tagsData, isLoading: tagsLoading } = useQuery({
    queryKey: ["learnserve-opportunity-interest-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("learnserve_opportunity_interest"),
    enabled: !!selectedLanguage,
  });

  const { data: genderData, isLoading: genderLoading } = useQuery({
    queryKey: ["opportunity-gender-choices", selectedLanguage],
    queryFn: () => getDropdownChoicesRequest("opportunity_gender"),
    enabled: !!selectedLanguage,
  });

  const { data: learningTypeData, isLoading: learningTypeLoading } = useQuery({
    queryKey: ["learning-type-choices"],
    queryFn: () => getDropdownChoicesRequest("learning_type"),
  });

  const { data: learnServeFormatData, isLoading: learnServeFormatLoading } =
    useQuery({
      queryKey: ["learn-serve-format-choices"],
      queryFn: () => getDropdownChoicesRequest("learn_serve_format"),
    });

  const { data: certificateTypeData, isLoading: certificateTypeLoading } =
    useQuery({
      queryKey: ["learn-serve-certificate-type-choices"],
      queryFn: () => getDropdownChoicesRequest("learn_serve_certificate_type"),
    });

  const tagOptions: Array<{ id: string; label: string }> =
    includeHeldGeneralTag(toChoiceTagOptions(tagsData?.data, selectedLanguage, (item) =>
      String(item.id)
    ), heldInterests, selectedLanguage);

  const genderOptions =
    (genderData?.data as Choice[] | undefined)?.map((item) =>
      toOption(item, selectedLanguage)
    ) || [];

  const learningTypeOptions: Array<{ label: string; value: string }> =
    (learningTypeData?.data as Choice[] | undefined)
      // Internships are organization-only; the other three are "development",
      // narrowed for a trainer to the types the admin approved (BE-95 G).
      ?.filter((item) =>
        item.value_en === "Internship"
          ? publishPermissions.internship
          : publishPermissions.development &&
            (publishPermissions.developmentTypes === null ||
              publishPermissions.developmentTypes.includes(item.value_en))
      )
      .sort(
        (a, b) =>
          LEARNING_TYPE_ORDER.indexOf(a.value_en) -
          LEARNING_TYPE_ORDER.indexOf(b.value_en)
      )
      .map((item) => toOption(item, selectedLanguage)) || [];

  const learnServeFormatOptions: Array<{ label: string; value: string }> =
    (learnServeFormatData?.data as Choice[] | undefined)?.map((item) =>
      toOption(item, selectedLanguage)
    ) || [];

  const certificateTypeOptions: Array<{ label: string; value: string }> =
    (certificateTypeData?.data as Choice[] | undefined)?.map((item) =>
      toOption(item, selectedLanguage)
    ) || [];

  return {
    tagOptions,
    genderOptions,
    learningTypeOptions,
    learnServeFormatOptions,
    certificateTypeOptions,

    tagsLoading,
    genderLoading,
    learningTypeLoading,
    learnServeFormatLoading,
    certificateTypeLoading,

    onlineFormatId: findOptionValue(
      learnServeFormatOptions,
      "online",
      selectedLanguage
    ),
    inPersonFormatId: findOptionValue(
      learnServeFormatOptions,
      "inPerson",
      selectedLanguage
    ),
    internshipTypeId: findOptionValue(
      learningTypeOptions,
      "internship",
      selectedLanguage
    ),
    courseTypeId: findOptionValue(
      learningTypeOptions,
      "course",
      selectedLanguage
    ),
    forsaCertificateId: certificateTypeOptions.find(
      (option) =>
        option.label === LABELS.forsaCertificate.en ||
        option.label === LABELS.forsaCertificate.ar
    )?.value,
  };
}
