import { opportunityNationalityOptions } from "@/data/Constants";
import { isValidKuwaitiIban } from "@/features/trainer/trainerRequest";
import { audienceAgeSchema, authoringCalendarDay, isAuthoringDayNotPast, isPositiveKwdPrice } from "@/features/shared/opportunityFormRules";
import * as Yup from "yup";
import i18n from "@/lib/i18n/config";
import {
  YupFlexibleUrl,
  YupNumberOnly,
  YupOptionalUrl,
  YupRequiredString,
  YupStringMaxLength,
  YupWhatsAppContact,
} from "@/features/shared/schemas";
import { richTextToPlain } from "@/features/opportunities/forms/richTextToPlain";

/**
 * Validation for the development-opportunity publish form.
 *
 * Lifted out of `LearnServeForm` unchanged — every rule, message key and
 * conditional is the same. It was 277 lines inside a `useMemo` in the middle of
 * a 2500-line component, which meant the form's *rules* could only be read by
 * scrolling past its markup. Nothing here touches the DOM or React, so it is a
 * plain function of the choices the form has resolved.
 *
 * The caller still memoizes on exactly the values below; they are named here so
 * a missing one is a type error rather than a stale schema.
 */
export interface LearnServeValidationContext {
  /** Master-choice ids, resolved from the dropdown payload. */
  inPersonFormatId?: string;
  onlineFormatId?: string;
  internshipTypeId?: string;
  courseTypeId?: string;
  existingEnglishTitle?: string | null;
  /** `getPublishPermissions(user).developmentPaid` — may this account charge? */
  developmentPaid: boolean;
  /** Whether the organizer's account type must attach a licence. */
  isLicenseRequired: boolean;
  /** Present when editing; absent when publishing something new. */
  id?: string | number | null;
  /**
   * Images already stored on the record. Only their *count* matters here: 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>;
}


export function buildLearnServeValidationSchema({
  inPersonFormatId,
  onlineFormatId,
  internshipTypeId,
  courseTypeId,
  existingEnglishTitle,
  developmentPaid,
  isLicenseRequired,
  id,
  modifiedOpportunityImages,
}: LearnServeValidationContext) {
  const titleSchema = YupStringMaxLength(255)
    .min(2, () => i18n.t("COMMON.EVENT_TITLE_MIN_LENGTH"))
    .concat(YupRequiredString);
  const descriptionSchema = Yup.string()
    .concat(YupRequiredString)
    .test(
      "is-not-empty-html",
      i18n.t("COMMON.REQUIRED.FIELD"),
      function (value) {
        if (!value) return false;
        // Strip markup and entities — an empty <p></p> is not real content
        const textContent = value
          .replace(/<[^>]*>/g, "")
          .replace(/&nbsp;/g, " ")
          .trim();
        return textContent.length > 0;
      }
    )
    .test(
      "description-min-length",
      i18n.t("COMMON.DESCRIPTION_MIN_LENGTH"),
      function (value) {
        if (!value) return true;
        const textContent = value
          .replace(/<[^>]*>/g, "")
          .replace(/&nbsp;/g, " ")
          .trim();
        return textContent.length >= 10;
      }
    );

  const optionalDescriptionSchema = Yup.string().test(
    "description-en-min-length",
    () => i18n.t("COMMON.DESCRIPTION_MIN_LENGTH"),
    (value) => {
      const text = richTextToPlain(value);
      return text.length === 0 || text.length >= 10;
    }
  );

  return Yup.object({
      title_ar: titleSchema,
      title_en: titleSchema.test("english-title", () => i18n.t("COMMON.ENGLISH_TITLE_REQUIRED"), value =>
        !value || (!!id && value.trim() === existingEnglishTitle?.trim()) || !/\p{Script=Arabic}/u.test(value)),
      description_ar: descriptionSchema,
      description_en: optionalDescriptionSchema,

      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);
          }
        ),
      startTime: Yup.string()
        .concat(YupRequiredString)
        .test(
          "start-time-valid",
          i18n.t("COMMON.INVALID_TIME_FORMAT"),
          (value) => !!value && /^[0-2][0-9]:[0-5][0-9]$/.test(value)
        ),
      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;
          }
        ),
      learningType: YupRequiredString,
      learnServeFormat: YupRequiredString,
      /*
       * Courses and internships are the two types that grant a certificate,
       * so both must declare which one. The API enforces exactly that
       * ("Certificate type is required for courses and internships"), and
       * this used to check internships only — a course submitted without a
       * certificate type passed here and came back a 422 with no field
       * highlighted.
       */
      certificateType: Yup.string().when("learningType", {
        is: (value: string) =>
          (!!internshipTypeId && value === internshipTypeId) ||
          (!!courseTypeId && value === courseTypeId),
        then: () => YupRequiredString,
        otherwise: () => Yup.string(),
      }),

      opportunity_nationality: Yup.string().when("learningType", {
        is: (value: string) => (!!courseTypeId && value === courseTypeId) || (!!internshipTypeId && value === internshipTypeId),
        then: schema => schema.oneOf(opportunityNationalityOptions.map(option => option.value), () => i18n.t("COMMON.REQUIRED.FIELD")).required(i18n.t("COMMON.REQUIRED.FIELD")),
        otherwise: schema => schema.notRequired(),
      }),

      location: Yup.string(),
      location_url: YupOptionalUrl.test(
        "location-url-host",
        () => i18n.t("COMMON.INVALID.URL"),
        (value) => {
          if (!value?.trim()) return true;
          try {
            const raw = value.trim();
            const url = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`);
            return (
              /^https?:$/.test(url.protocol) &&
              !url.username && !url.password &&
              url.hostname.includes(".") &&
              url.hostname.split(".").every(label =>
                /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label)
              )
            );
          } catch {
            return false;
          }
        }
      ).test(
        "location-provided",
        () => i18n.t("COMMON.REQUIRED.FIELD"),
        function (value) {
          const isInPersonFormat =
            !!inPersonFormatId &&
            String(this.parent.learnServeFormat) === String(inPersonFormatId);
          if (!isInPersonFormat) return true;
          return Boolean(value?.trim());
        }
      ),
      meetingLink: Yup.string().when(
        "learnServeFormat",
        ([learnServeFormat], schema) =>
          learnServeFormat &&
          onlineFormatId &&
          String(learnServeFormat) === String(onlineFormatId)
            ? schema.concat(YupFlexibleUrl)
            : schema
      ),
      // Both development and volunteering require a valid WhatsApp contact.
      whatsappLink: YupWhatsAppContact.concat(YupRequiredString),

      price: Yup.string().when(["is_paid", "learningType"], ([isPaid, learningType], schema) =>
        isPaid === "true" &&
        developmentPaid &&
        !(internshipTypeId && learningType === internshipTypeId)
          ? schema
              .concat(YupRequiredString)
              .test(
                "price-positive",
                () => i18n.t("COMMON.PRICE_KWD_VALID"),
                isPositiveKwdPrice
              )
          : schema
      ),
      /*
       * The payout account, only while `PayoutBankFields` shows it — a paid
       * opportunity from an organization with no account on file, or one
       * that chose to change it. Saved to the profile before submit.
       */
      payout_bank_id: Yup.number().typeError(() => i18n.t("COMMON.VALID_NUMBERS")).transform((value, original) => original === "" ? undefined : value).when(["is_paid", "payout_bank_needed"], ([isPaid, needed], schema) =>
        isPaid === "true" && needed ? schema.integer(() => i18n.t("COMMON.VALID_NUMBERS")).positive(() => i18n.t("COMMON.VALID_NUMBERS")).required(() => i18n.t("COMMON.REQUIRED.FIELD")) : schema
      ),
      payout_bank_name: Yup.string().when(["is_paid", "payout_bank_needed"], ([isPaid, needed], schema) =>
        isPaid === "true" && needed ? schema.concat(YupRequiredString).max(100, () => `${i18n.t("COMMON.MUST.BE.ATMOST")} 100 ${i18n.t("COMMON.CHARACTERS")}`) : schema
      ),
      payout_bank_holder: Yup.string().when(["is_paid", "payout_bank_needed"], ([isPaid, needed], schema) =>
        isPaid === "true" && needed ? schema.concat(YupRequiredString).max(150, () => `${i18n.t("COMMON.MUST.BE.ATMOST")} 150 ${i18n.t("COMMON.CHARACTERS")}`) : schema
      ),
      payout_iban: Yup.string().when(["is_paid", "payout_bank_needed"], ([isPaid, needed], schema) =>
        isPaid === "true" && needed
          ? schema
              .concat(YupRequiredString)
              .test("iban-valid", () => i18n.t("COMMON.IBAN_INVALID_KW"), (value) => isValidKuwaitiIban(value ?? ""))
          : schema
      ),
      participantsNeeded: YupNumberOnly,
      gender: Yup.string().concat(YupRequiredString),
      age: audienceAgeSchema(true),
      opportunity_images: Yup.mixed().test(
        "has-files",
        i18n.t("COMMON.REQUIRED.FIELD"),
        (value) =>
          (Array.isArray(value) && value.length > 0) ||
          modifiedOpportunityImages.length > 0
      ),
      _interests: Yup.array()
        .of(Yup.string())
        .min(1, i18n.t("COMMON.REQUIRED.FIELD")),
      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;
        }
      ),
    });
}
