import * as Yup from "yup";

import i18n from "@/lib/i18n/config";
import { calculateAgeFromDob } from "@/features/shared/schemas/fields";
import { toWesternDigits } from "@/lib/digits";

/**
 * The individual-trainer request (BE-95) — shared by the signup form and the
 * account-settings card.
 *
 * Off until BE-95 ships: `RejectsUnknownWriteKeys` 422s a whole request that
 * carries a key the API does not know, so sending `show_real_name` or the
 * trainer block early would break signup for everyone. Flip this once the
 * backend confirms the fields below.
 *
 * **On since 2026-10-10**, at the client's request for the volunteer signup
 * (show-name toggle, "offer development opportunities", course certificate,
 * bank account). Re-verified against the backend at 7277a36: `RegisterRequest`
 * and `AuthService::register` accept and persist every field below, and
 * `TrainerRequestController` applies the same KW-IBAN and holder-name rules
 * the schema now mirrors. The browser checks listed further down still apply.
 *
 * What was verified in the backend source for this pass:
 *
 *  - `Api/Volunteer/TrainerRequestController` exists, with
 *    `GET /trainer-request/settings/` (public), and `GET` / `POST
 *    /trainer-request/` behind auth;
 *  - `trainer_types` is validated as `['required','array','min:1']` with
 *    `Rule::in(['course','workshop','consultation'])` — the same three slugs
 *    as `TRAINER_TYPES` below — and `store()` writes `trainer_status:
 *    'pending'` alongside them;
 *  - `show_real_name` is validated by `RegisterRequest`,
 *    `VolunteerProfileUpdateRequest` and the trainer request itself, and
 *    persisted by `VolunteerProfileController::update()` — which additionally
 *    refuses to let an **approved** trainer turn it off (422, field-scoped).
 *
 * The 422 risk the gate was protecting against is also gone for the profile
 * save: `RejectsUnknownWriteKeys` is only used by the three
 * opportunity/event controllers.
 *
 * ---
 *
 * **What flipping this to `true` would expose**, by call site:
 *
 *  - `IndividualRegistrationForm` — the "I want to be a trainer" question and,
 *    when answered yes, the trainer block on the sign-up form. This is the one
 *    with real blast radius: `useIndividualRegistration` then switches the
 *    whole registration from a JSON body to `FormData` so the certificate can
 *    ride along, and adds `show_real_name` to the payload. A new volunteer who
 *    does *not* ask to be a trainer is unaffected — `requestsTrainer` is
 *    false, so the JSON path is unchanged.
 *  - `IndividualRegistrationForm` also gains the `trainer-request/settings/`
 *    query (`enabled: TRAINER_REQUEST_LIVE`), which is public and read-only.
 *  - `VolunteerAccountInformation` / `VolunteerGuardianSection` — the trainer
 *    request card in account settings, including the IBAN field, which the
 *    client restricted to this flow only.
 *  - `useVolunteerAccountSubmit` starts sending `show_real_name` on a profile
 *    save.
 *
 * **What has to be verified before flipping**, none of which can be done from
 * the source:
 *
 *  1. a sign-up with the trainer block filled in, including a PDF certificate,
 *     actually completes — this is the multipart switch, and the only path on
 *     which registration changes transport;
 *  2. a sign-up *without* the trainer answer still completes, to confirm the
 *     JSON path did not move;
 *  3. an under-24 applicant is refused by both sides (`MIN_TRAINER_AGE` here
 *     and the server's own rule) with a message the reader can act on;
 *  4. the IBAN field's server-side check — `RegisterRequest` validates the
 *     Kuwaiti IBAN format *and* its mod-97 checksum, so a plausible-looking
 *     but invalid number must surface as a field error, not a toast;
 *  5. an approved trainer cannot turn `show_real_name` off (the server returns
 *     a field-scoped 422) and the form shows that where the reader expects it;
 *  6. the request card's state after submitting — `trainer_status: 'pending'`
 *     has to render as pending rather than as "not requested".
 */
export const TRAINER_REQUEST_LIVE = true;

/** The client's hard rule, enforced server-side too. */
export const MIN_TRAINER_AGE = 24;

export const TRAINER_CERTIFICATE_MAX_BYTES = 5 * 1024 * 1024;
export const TRAINER_CERTIFICATE_TYPES = [
  "application/pdf",
  "image/jpeg",
  "image/png",
];

/**
 * Wire slugs. Course is the only one that asks for a qualification file;
 * workshops and spaces never do. `valueEn` is the learning-type choice each
 * one corresponds to on the publish form.
 */
export const TRAINER_TYPES = [
  { slug: "course", valueEn: "Course", labelKey: "COMMON.TRAINER_TYPE_COURSE" },
  { slug: "workshop", valueEn: "Class/Workshop", labelKey: "COMMON.TRAINER_TYPE_WORKSHOP" },
  { slug: "consultation", valueEn: "Consultation", labelKey: "COMMON.TRAINER_TYPE_CONSULTATION" },
] as const;

export type TrainerTypeSlug = (typeof TRAINER_TYPES)[number]["slug"];
export type TrainerStatus = "none" | "pending" | "approved" | "rejected";

/** The switches the client controls from the dashboard (BE-95). */
export interface TrainerRequestSettings {
  course_certificate_required: boolean;
  bank_details_required: boolean;
  /**
   * BE-95 — the slugs `POST /trainer-request/` will accept, straight from the
   * API, so this list cannot drift from the server's `Rule::in`.
   *
   * It is slugs only; the label and the publish-form learning type each slug
   * maps to stay in `TRAINER_TYPES` below, because the endpoint does not send
   * them. Read it through `offeredTrainerTypes()` rather than directly — an
   * older deployment omits the key, and that has to mean "offer all three"
   * rather than "offer none".
   */
  trainer_types?: TrainerTypeSlug[] | null;
}

/**
 * Which qualifications the form may offer: the local list, narrowed to what
 * the API says it accepts.
 *
 * A value the server no longer accepts would 422 the whole submission, and an
 * absent or empty list means we were not told — in which case all three are
 * offered, which is what happened before BE-95 added the field.
 */
export function offeredTrainerTypes(
  settings?: TrainerRequestSettings | null
): typeof TRAINER_TYPES[number][] {
  const accepted = settings?.trainer_types;
  if (!accepted || accepted.length === 0) return [...TRAINER_TYPES];
  return TRAINER_TYPES.filter((type) => accepted.includes(type.slug));
}

/**
 * BE-186 (backend `1983649`): an approved trainer keeps the approved types and
 * may ask for more; only the new ones go to review (`trainer_pending_types`),
 * and rejecting them leaves the trainer approved with `trainer_rejected_reason`.
 */
export interface TrainerRequestProgress {
  trainer_status: TrainerStatus;
  trainer_types?: TrainerTypeSlug[] | null;
  trainer_pending_types?: TrainerTypeSlug[] | null;
}

/** Types the form may still offer: an approved type is never asked for again. */
export function requestableTrainerTypes(
  settings: TrainerRequestSettings | null | undefined,
  request: TrainerRequestProgress | null | undefined
): typeof TRAINER_TYPES[number][] {
  const approved = request?.trainer_status === "approved" ? request.trainer_types ?? [] : [];
  return offeredTrainerTypes(settings).filter((type) => !approved.includes(type.slug));
}

/** Whether the request form can be opened: first request, after a rejection, or more types. */
export function canRequestTrainerTypes(
  settings: TrainerRequestSettings | null | undefined,
  request: TrainerRequestProgress | null | undefined
): boolean {
  const status = request?.trainer_status ?? "none";
  if (status === "none" || status === "rejected") return true;
  return status === "approved"
    && (request?.trainer_pending_types ?? []).length === 0
    && requestableTrainerTypes(settings, request).length > 0;
}

/** Until the settings endpoint answers, assume the stricter design (both "*"). */
export const DEFAULT_TRAINER_SETTINGS: TrainerRequestSettings = {
  course_certificate_required: true,
  bank_details_required: true,
};

export interface TrainerRequestValues {
  trainer_types: TrainerTypeSlug[];
  trainer_certificate: File | null;
  bank_account_holder_name: string;
  bank_id?: number | "";
  bank_name: string;
  iban: string;
  iban_confirmation: string;
  bank_account_ownership: boolean;
}

export const emptyTrainerRequestValues: TrainerRequestValues = {
  trainer_types: [],
  trainer_certificate: null,
  bank_account_holder_name: "",
  bank_id: "",
  bank_name: "",
  iban: "",
  iban_confirmation: "",
  bank_account_ownership: false,
};

/* Arabic-Indic digits from an Arabic keyboard are converted: the API's
   IbanValidator only strips spaces, so «KW٨١…» was refused as invalid. */
export const normalizeIban = (value: string) =>
  toWesternDigits(value).replace(/\s+/g, "").toUpperCase();

/**
 * ISO 13616 check: right length for its country, then mod-97 on the
 * rearranged digits. Kuwaiti IBANs are 30 characters; other countries are
 * accepted at their own length so an expatriate's home account is not
 * refused here — the backend has the final word.
 */
const IBAN_LENGTHS: Record<string, number> = {
  KW: 30, SA: 24, AE: 23, BH: 22, QA: 29, OM: 23, EG: 29, JO: 30, LB: 28,
};

export function isValidIban(raw: string): boolean {
  const iban = normalizeIban(raw);
  if (!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(iban)) return false;
  const expected = IBAN_LENGTHS[iban.slice(0, 2)];
  if (expected && iban.length !== expected) return false;

  const rearranged = iban.slice(4) + iban.slice(0, 4);
  let remainder = 0;
  for (const char of rearranged) {
    const digits = /[A-Z]/.test(char) ? String(char.charCodeAt(0) - 55) : char;
    for (const digit of digits) {
      remainder = (remainder * 10 + Number(digit)) % 97;
    }
  }
  return remainder === 1;
}

/**
 * Every payout IBAN the API stores must be Kuwaiti: `App\Support\IbanValidator`
 * refuses anything but `^KW[0-9A-Z]{28}$` (plus mod-97), and it backs the
 * trainer request, the organization profile (BE-117) and the payout bank
 * change request alike. Use this, not the permissive `isValidIban`, for any
 * IBAN that is sent to the API.
 */
export function isValidKuwaitiIban(raw: string): boolean {
  const iban = normalizeIban(raw);
  return /^KW[0-9A-Z]{28}$/.test(iban) && isValidIban(iban);
}

/**
 * Bank account holder matching — the client's rule (answers PDF p.3, item 11):
 *  - the first name must match, and the family (last) name must match;
 *  - middle names may be left out or abbreviated: registered «محمد علي حسن»
 *    accepts «محمد حسن», «محمد ع حسن» and «محمد علي حسن», but not «علي حسن»;
 *  - simple spelling differences pass: case, accents, tashkeel and the
 *    tatweel are ignored, Arabic letter variants unified (أ/إ/آ/ٱ→ا, ى→ي,
 *    ة→ه, ؤ→و, ئ→ي) and a split or joined compound counts once
 *    («عبدالله» / «عبد الله»);
 *  - an organization's holder must be its registered (licence) name.
 *
 * A mismatch is not refused: the client sends it to the administration for
 * manual review. The forms therefore *warn* (`HolderReviewNotice`) and still
 * submit; whatever the server answers is shown as it is.
 */
const ARABIC_VARIANTS: Record<string, string> = {
  "أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا", "ى": "ي", "ة": "ه", "ؤ": "و", "ئ": "ي",
};

export function holderNameWords(name: string): string[] {
  const folded = String(name ?? "")
    .toLowerCase()
    .replace(/[أإآٱىةؤئ]/g, (char) => ARABIC_VARIANTS[char])
    .normalize("NFD")
    .replace(/[\p{Mn}\u0640]+/gu, "");
  return folded.split(/[^\p{L}]+/u).filter(Boolean);
}

/** Every way of reading the words with neighbours joined («عبد الله» → «عبدالله»). */
function segmentations(words: string[]): string[][] {
  if (words.length <= 1) return [words];
  const out: string[][] = [];
  for (const rest of segmentations(words.slice(1))) {
    out.push([words[0], ...rest]);
    out.push([words[0] + rest[0], ...rest.slice(1)]);
  }
  return out;
}

/**
 * Holder middles must appear in order among the registered middles, each whole
 * or as an abbreviation. A Fursa account stores only first and last name, so a
 * registered name with no middles says nothing about them: the bank's full
 * name («محمد علي حسن» for «محمد حسن») fits, as the backend's
 * `AccountHolderName::matches()` also accepts it.
 */
function middlesFit(holder: string[], registered: string[]): boolean {
  if (registered.length === 0) return true;
  let at = 0;
  for (const word of holder) {
    while (at < registered.length && !registered[at].startsWith(word)) at += 1;
    if (at === registered.length) return false;
    at += 1;
  }
  return true;
}

export function holderMatchesRegisteredName(holder: string, registeredName: string): boolean {
  const holderWords = holderNameWords(holder);
  const realWords = holderNameWords(registeredName);
  if (holderWords.length === 0 || realWords.length === 0) return false;
  if (holderWords.join("") === realWords.join("")) return true;
  if (holderWords.length < 2 || realWords.length < 2) return false;
  return segmentations(holderWords).some((h) =>
    segmentations(realWords).some((r) =>
      h.length >= 2 && r.length >= 2 &&
      h[0] === r[0] && h[h.length - 1] === r[r.length - 1] &&
      middlesFit(h.slice(1, -1), r.slice(1, -1))
    )
  );
}

/** An organization: the holder is its registered name, spelling and spacing aside. */
export function holderMatchesOrganizationName(holder: string, registeredName: string): boolean {
  const holderWords = holderNameWords(holder);
  return holderWords.length > 0 && holderWords.join("") === holderNameWords(registeredName).join("");
}

export function holderMatchesRealName(
  holder: string,
  firstName: string,
  lastName: string
): boolean {
  return holderMatchesRegisteredName(holder, `${firstName} ${lastName}`);
}

/**
 * Who may ask for a payout account change (`POST /payout-bank-change-requests/`).
 * Mirrors `PayoutBankAccountService::subject()`: an organization, or an
 * individual with any trainer request on record — pending and rejected
 * included. `is_trainer` only means *approved*, and gating on it left a
 * rejected applicant whose account is on file with no way to change it.
 */
export function canRequestPayoutBankChange(
  account: { user_type?: string | null; trainer_status?: string | null } | null | undefined
): boolean {
  if (!account) return false;
  if (account.user_type === "organization") return true;
  return !!account.trainer_status && account.trainer_status !== "none";
}

/**
 * The account a trainer request can rely on instead of a new one: `GET
 * /trainer-request/` exposes only its last four digits and bank name. Once one
 * is on file the server stops requiring the bank block (BE-187) and refuses a
 * different IBAN there (`use_change_request`) — a change goes through the
 * payout bank change request instead.
 */
export function trainerBankOnFile(
  request: { iban_last4?: string | null; bank_name?: string | null } | null | undefined
): { last4: string; bankName: string | null } | null {
  const last4 = request?.iban_last4?.trim();
  if (!last4) return null;
  return { last4, bankName: request?.bank_name?.trim() || null };
}

/** The bank keys of the trainer block — used to reveal it when the server asks for them. */
export const TRAINER_BANK_FIELDS = [
  "bank_account_holder_name",
  "bank_id",
  "bank_name",
  "iban",
  "iban_confirmation",
  "bank_account_ownership",
] as const;

const t = (key: string, options?: Record<string, unknown>) => i18n.t(key, options);

/**
 * Field rules for the trainer block. `active` says whether the block is being
 * submitted at all — on the signup form it is behind a toggle, so every rule
 * collapses to "not required" while that toggle is off.
 */
export function trainerRequestSchema(
  settings: TrainerRequestSettings,
  active: (parent: Record<string, unknown>) => boolean = () => true,
  /** An account is already on file (see `trainerBankOnFile`): the bank block is optional. */
  { bankOnFile = false }: { bankOnFile?: boolean } = {}
) {
  const bankRequired = !bankOnFile;

  return {
    trainer_types: Yup.array()
      .of(Yup.string())
      .test("trainer-types", () => t("COMMON.TRAINER_TYPES_REQUIRED"), function (value) {
        return !active(this.parent) || (value?.length ?? 0) > 0;
      }),
    trainer_certificate: Yup.mixed<File>()
      .nullable()
      .test("certificate-required", () => t("COMMON.TRAINER_CERTIFICATE_REQUIRED"), function (value) {
        if (!active(this.parent)) return true;
        const needsCourse = (this.parent.trainer_types ?? []).includes("course");
        if (!needsCourse) return true;
        return value instanceof File;
      })
      .test("certificate-type", () => t("COMMON.TRAINER_CERTIFICATE_TYPE"), (value) =>
        !(value instanceof File) || TRAINER_CERTIFICATE_TYPES.includes(value.type)
      )
      .test("certificate-size", () => t("COMMON.TRAINER_CERTIFICATE_SIZE"), (value) =>
        !(value instanceof File) || value.size <= TRAINER_CERTIFICATE_MAX_BYTES
      ),
    bank_account_holder_name: Yup.string()
      .max(100)
      .test("holder-required", () => t("COMMON.REQUIRED.FIELD"), function (value) {
        return !active(this.parent) || !bankRequired || !!value?.trim();
      }),
    bank_id: Yup.mixed<number | "">().test("bank-selected", () => t("COMMON.REQUIRED.FIELD"), function (value) {
      return !active(this.parent) || !bankRequired || !!this.parent.bank_name?.trim() || (typeof value === "number" && Number.isInteger(value) && value > 0);
    }),
    bank_name: Yup.string()
      .max(100)
      .test("bank-required", () => t("COMMON.REQUIRED.FIELD"), function (value) {
        return !active(this.parent) || !bankRequired || !!value?.trim() || (typeof this.parent.bank_id === "number" && Number.isInteger(this.parent.bank_id) && this.parent.bank_id > 0);
      }),
    iban: Yup.string()
      .test("iban-required", () => t("COMMON.REQUIRED.FIELD"), function (value) {
        return !active(this.parent) || !bankRequired || !!value?.trim();
      })
      .test("iban-valid", () => t("COMMON.IBAN_INVALID_KW"), function (value) {
        return !active(this.parent) || !value?.trim() || isValidKuwaitiIban(value);
      }),
    iban_confirmation: Yup.string().test(
      "iban-match",
      () => t("COMMON.IBAN_MISMATCH"),
      function (value) {
        if (!active(this.parent) || !this.parent.iban?.trim()) return true;
        return normalizeIban(value ?? "") === normalizeIban(this.parent.iban);
      }
    ),
    bank_account_ownership: Yup.boolean().test(
      "ownership",
      () => t("COMMON.BANK_OWNERSHIP_REQUIRED"),
      function (value) {
        // Only asked when an account is actually being given.
        if (!active(this.parent) || !this.parent.iban?.trim()) return true;
        return value === true;
      }
    ),
  };
}

/** The age rule, as a test to attach to `dob` wherever the block can be on. */
export function isOldEnoughForTrainer(dob: string | null | undefined): boolean {
  if (!dob) return false;
  const age = calculateAgeFromDob(dob);
  return age !== null && age >= MIN_TRAINER_AGE;
}

/** Appends the block to a multipart body, in the field names BE-95 specifies. */
export function appendTrainerRequest(formData: FormData, values: TrainerRequestValues) {
  values.trainer_types.forEach((slug) => formData.append("trainer_types[]", slug));
  if (values.trainer_types.includes("course") && values.trainer_certificate) {
    formData.append("trainer_certificate", values.trainer_certificate);
  }
  if (values.iban.trim()) {
    formData.append("bank_account_holder_name", values.bank_account_holder_name.trim());
    if (typeof values.bank_id === "number" && Number.isInteger(values.bank_id) && values.bank_id > 0) {
      formData.append("bank_id", String(values.bank_id));
    } else {
      formData.append("bank_name", values.bank_name.trim());
    }
    formData.append("iban", normalizeIban(values.iban));
    formData.append("iban_confirmation", normalizeIban(values.iban_confirmation));
    formData.append("bank_account_ownership", values.bank_account_ownership ? "1" : "0");
  }
}
