import moment from "moment";
import * as Yup from "yup";
import i18n from "@/lib/i18n/config";
import { OPPORTUNITY_MIN_AGE, OPPORTUNITY_MAX_AGE } from "@/data/Constants";

/** Date pickers store either a calendar day or the ISO instant of local midnight. */
export function authoringCalendarDay(value: string | Date): string {
  if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
    return moment(value, "YYYY-MM-DD", true).isValid() ? value : "";
  }
  const parsed = moment(value);
  return parsed.isValid() ? parsed.locale("en").format("YYYY-MM-DD") : "";
}

/** Compare the selected calendar day with today in Kuwait, never UTC midnight. */
export function isAuthoringDayNotPast(value?: string, now = moment()): boolean {
  if (!value) return true;
  const day = authoringCalendarDay(value);
  return Boolean(day && day >= now.clone().utcOffset(180).locale("en").format("YYYY-MM-DD"));
}

/** Date-picker bounds are local Date objects representing Kuwait's calendar day. */
export function kuwaitDatePickerMinimum(now = moment()): Date {
  const day = now.clone().utcOffset(180);
  return new Date(day.year(), day.month(), day.date());
}

export function clampAudienceAge(value: number): number {
  return Math.min(Math.max(value, OPPORTUNITY_MIN_AGE), OPPORTUNITY_MAX_AGE);
}

/**
 * KWD authoring uses whole fils; do not silently round a participant's price.
 * Same shape as backend `App\Rules\PlainPrice` (`1983649`): up to 7 integer
 * digits, an optional point with 1–3 decimals, nothing else (no `.5`, no exponent).
 */
export function isPositiveKwdPrice(value?: string): boolean {
  const amount = value?.trim() ?? "";
  return /^\d{1,7}(?:\.\d{1,3})?$/.test(amount) && Number(amount) > 0;
}

/** Opportunities require a minimum age; a blank maximum means no upper limit. Events may omit both. */
export function audienceAgeSchema(required: boolean) {
  return Yup.array()
    .of(Yup.number().nullable()
      .typeError(() => i18n.t("COMMON.VALID_NUMBERS"))
      .integer(() => i18n.t("COMMON.VALID_NUMBERS"))
      .min(OPPORTUNITY_MIN_AGE, () => i18n.t("COMMON.AUDIENCE_AGE_MIN", { age: OPPORTUNITY_MIN_AGE }))
      .max(OPPORTUNITY_MAX_AGE, () => i18n.t("COMMON.AUDIENCE_AGE_MAX", { age: OPPORTUNITY_MAX_AGE })))
    .test("required-age-bounds", () => i18n.t("COMMON.REQUIRED.FIELD"), value =>
      !required || (Array.isArray(value) && value[0] != null))
    .test("ordered-age-bounds", () => i18n.t("COMMON.END_AGE_MUST_BE_GREATER_THAN_START_AGE"), value =>
      !value || value[0] == null || value[1] == null || value[0] <= value[1]);
}
