import * as Yup from "yup";
import i18n from "@/lib/i18n/config";
import { audienceAgeSchema, authoringCalendarDay, isAuthoringDayNotPast } from "@/features/shared/opportunityFormRules";
import { YupNumberOnly, YupRequiredString, YupStringMaxLength, YupWhatsAppContact } from "@/features/shared/schemas";
import { richTextToPlain } from "@/features/opportunities/forms/richTextToPlain";

interface VolunteerValidationContext {
  /** Whether this organizer's account type must attach a permit. */
  isLicenseRequired: boolean;
  /**
   * Files already stored on the record. Only their *count* matters: an edit
   * that leaves the existing upload untouched still satisfies a "required"
   * rule even though the file input is empty.
   */
  /** Unused since BE-111 — kept so callers need not change. */
  modifiedLicenseImage?: ReadonlyArray<unknown>;
  modifiedOpportunityImages: ReadonlyArray<unknown>;
  /** The "about the opportunity" section is not shown for every publisher. */
  showOpportunitySection: boolean;
  /** Present when editing: an untouched stored licence still counts. */
  id?: string | number | null;
}

/**
 * Validation for the volunteering publish form.
 *
 * Lifted out of `VolunteerForm` unchanged — every rule, message key and
 * conditional is the same. Nothing here touches the DOM or React, so it is a
 * plain function of the few facts the rules depend on.
 */
export function buildVolunteerValidationSchema({
  isLicenseRequired,
  modifiedOpportunityImages,
  showOpportunitySection,
  id,
}: VolunteerValidationContext) {

  // The Arabic description — the one always on screen, and always required.
  const descriptionSchema = Yup.string()
    .concat(YupRequiredString)
    .test(
      "is-not-empty-html",
      i18n.t("COMMON.REQUIRED.FIELD"),
      (value) => richTextToPlain(value).length > 0
    )
    .test(
      "description-min-length",
      i18n.t("COMMON.DESCRIPTION_MIN_LENGTH"),
      (value) => {
        const textContent = richTextToPlain(value);
        // Emptiness is the required rule's business, not this one's.
        return textContent.length === 0 || textContent.length >= 10;
      }
    );

  /*
   * The English description is optional, so it cannot reuse the rule above —
   * that one is built on `YupRequiredString`. The length floor still applies
   * to anything actually written, which is the part worth keeping: a
   * two-word English description is worse than none, because the submit
   * handler would otherwise have copied the full Arabic one across.
   */
  const optionalDescriptionSchema = Yup.string().test(
    "description-min-length",
    i18n.t("COMMON.DESCRIPTION_MIN_LENGTH"),
    (value) => {
      const textContent = richTextToPlain(value);
      return textContent.length === 0 || textContent.length >= 10;
    }
  );

  return Yup.object({
    /*
     * Required, and deliberately so. The submit handler maps anything that is
     * not the literal "public" to `is_public: 0`, so leaving this untouched
     * used to create a PRIVATE opportunity silently — it never appeared in any
     * listing, and the backend additionally refuses registrations for private
     * opportunities, so it was both invisible and unjoinable with no signal to
     * the organizer. Defaulting the other way would be just as wrong (an
     * opportunity meant to be private would go public), so the choice is
     * forced instead. Only organizations see the field; volunteers always send
     * `is_public: 1`, which is why this is conditional.
     */
    isPrivate: showOpportunitySection
      ? Yup.string().concat(YupRequiredString)
      : Yup.string().notRequired(),
    title_ar: YupStringMaxLength(255)
      .min(2, () => i18n.t("COMMON.EVENT_TITLE_MIN_LENGTH"))
      .concat(YupRequiredString),
    /*
     * Optional, and built from scratch rather than from `YupStringMaxLength` —
     * that helper descends from `YupRequiredString`, so every rule composed
     * out of it is required no matter what is chained on afterwards. The
     * length and whitespace rules still apply to whatever is actually typed;
     * `excludeEmptyString` keeps them off an untouched field.
     */
    title_en: Yup.string()
      .max(
        400,
        () =>
          `${i18n.t("COMMON.MUST.BE.ATMOST")}400${i18n.t("COMMON.CHARACTERS")}`
      )
      .matches(/^(?!\s)/, {
        message: () => i18n.t("COMMON.NO.START.SPACE"),
        excludeEmptyString: true,
      })
      .matches(/(?<!\s)$/, {
        message: () => i18n.t("COMMON.NO.END.SPACE"),
        excludeEmptyString: true,
      })
      .test(
        "title-en-min-length",
        () => i18n.t("COMMON.EVENT_TITLE_MIN_LENGTH"),
        (value) => !value || value.trim().length >= 2
      ),

    registrationDeadlineHours: Yup.number().transform((v, raw) => raw === "" ? null : v).nullable().typeError(() => i18n.t("COMMON.VALID_NUMBERS")).integer(() => i18n.t("COMMON.VALID_NUMBERS")).min(1, () => i18n.t("COMMON.MINIMUM_VALUE", { value: 1 })).when("registrationDeadlineEnabled", { is: true, then: schema => schema.required(i18n.t("COMMON.REQUIRED.FIELD")) }),
    dueDate: Yup.string()
      .test("due-date-in-future", i18n.t("COMMON.DATE_MUST_BE_FUTURE"), value => isAuthoringDayNotPast(value))
      .test(
        "due-date-before-start-date",
        i18n.t("COMMON.DUE_DATE_BEFORE_START"),
        function (value) {
          const startDate = this.parent.startDate;
          return !value || !startDate || new Date(value) < new Date(startDate);
        }
      ),
    startDate: Yup.string()
      .concat(YupRequiredString)
      .test("start-date-in-future", i18n.t("COMMON.DATE_MUST_BE_FUTURE"), value => isAuthoringDayNotPast(value)),
    endDate: Yup.string()
      .concat(YupRequiredString)
      .test("end-date-in-future", i18n.t("COMMON.DATE_MUST_BE_FUTURE"), value => isAuthoringDayNotPast(value))
      .test(
        "end-date-after-start-date",
        i18n.t("COMMON.END_DATE_AFTER_START"),
        function (value) {
          const startDate = this.parent.startDate;
          if (!startDate || !value) return true;
          return authoringCalendarDay(value) >= authoringCalendarDay(startDate);
        }
      ),
    /*
     * `startDate` / `endDate` already carry the future and ordering rules, and
     * they are derived from this array, so all this has to catch is an empty
     * calendar — which in scattered mode is otherwise invisible, since there
     * is no separate end-date field left for the organiser to notice missing.
     */
    scheduleDates: Yup.array()
      .of(Yup.string())
      .min(1, () => i18n.t("COMMON.REQUIRED.FIELD")),
    participantsNeeded: YupNumberOnly,
    volunteerCategory: Yup.string().concat(YupRequiredString),
    // Only charity opportunities carry a beneficiaries count; the backend nulls
    // it for the other categories, so it is never required.
    beneficiariesCount: Yup.string().test(
      "beneficiaries-count-is-number",
      i18n.t("COMMON.ONLY_NUMBERS"),
      (value) => !value || /^\d+$/.test(value)
    ),
    /*
     * BE-109 — required, which only ever bites the record whose retired
     * audience `volunteerInitialValues` just blanked: a new form starts on
     * «كل الجنسيات» and every other saved value survives the load. The
     * API's own rule is `nullable`, so this is stricter on purpose — it is
     * the one case where sending nothing would lose information the organizer
     * had expressed, rather than express nothing.
     */
    opportunity_nationality: YupRequiredString,
    age: audienceAgeSchema(true),
    startTime: Yup.string().concat(YupRequiredString),
    endTime: Yup.string()
      .concat(YupRequiredString)
      .test(
        "end-time-after-start-time",
        i18n.t("COMMON.END_TIME_AFTER_START"),
        function (value) {
          const startTime = this.parent.startTime;
          if (!startTime || !value) return true;
          const [startHour, startMinute] = startTime.split(":").map(Number);
          const [endHour, endMinute] = value.split(":").map(Number);
          return endHour * 60 + endMinute > startHour * 60 + startMinute;
        }
      ),
    gender: Yup.string().concat(YupRequiredString),

    locationUrl: Yup.string().url(() => i18n.t("COMMON.INVALID_URL")).concat(YupRequiredString),
    location: Yup.string().test("attendance-location-pin", () => i18n.t("COMMON.ATTENDANCE_LOCATION_NEEDS_PIN"), function () {
      return !this.parent.requiresAttendanceLocation || (this.parent.latitude !== "" && this.parent.longitude !== "");
    }),
    link: YupWhatsAppContact.concat(YupRequiredString),
    description_ar: descriptionSchema,
    description_en: optionalDescriptionSchema,
    _interests: Yup.array()
      .of(Yup.string())
      .min(1, i18n.t("COMMON.REQUIRED.FIELD")),
    opportunity_images: Yup.mixed().test(
      "has-files",
      i18n.t("COMMON.REQUIRED.FIELD"),
      function (value) {
        return (
          (Array.isArray(value) && value.length > 0) ||
          modifiedOpportunityImages.length > 0
        );
      }
    ),
    license_image: Yup.mixed().test(
      "license-image-required",
      i18n.t("COMMON.REQUIRED.FIELD"),
      function (value) {
        if (!isLicenseRequired) return true;

        /*
         * Editing or republishing: the server keeps the stored licence unless
         * `license_image_removed` is sent (`RepublishMedia::apply()`; a
         * republish copies the source's), so an untouched one satisfies the
         * rule even when it is not shown. BE-111: the API currently hides
         * `license_image` from the owning organization, so
         * `modifiedLicenseImage` is empty here and the old check demanded a
         * re-upload on every edit. Removing it on purpose still requires a
         * new file.
         */
        if (id && this.parent.license_image_removed === false) {
          return true;
        }
        return value instanceof File && value.size > 0;
      }
    ),
  });
}
