import * as Yup from "yup";
import {
  YupDigitsOnlyOptional,
  createPhoneNumberSchema,
  YupWhatsAppContact,
} from "@/features/shared/schemas";
import { type OrgTypeOption } from "@/data/orgTypes";
import {
  areDocumentsWithinSizeLimit,
  licenseUploadRequiredFor,
  licenseNumberRequiredFor,
  whenValue,
  type YupWhenValue,
} from "@/features/shared/formRules";

/**
 * The organization account form's rules.
 *
 * A function, not a constant, because the nickname rule has to know the saved
 * value (re-typing your own nickname is not a conflict) and the latest
 * availability answer.
 */
export function buildOrganizerAccountValidation({
  t,
  initialNickname,
  nicknameAvailable,
  orgTypeOptions,
  keptDocIds,
}: {
  t: (key: string, options?: Record<string, unknown>) => string;
  initialNickname?: string;
  nicknameAvailable?: boolean | null;
  /** Needed to tell a volunteer team from an organization — see the licence rule. */
  orgTypeOptions: OrgTypeOption[];
  /** Ids of already-stored documents the organizer chose to keep. */
  keptDocIds: number[];
}) {
  return Yup.object({
    company_name: Yup.string().trim().required(t("COMMON.REQUIRED.FIELD")).max(255),
    phone_number: Yup.string().when(
      "country_code",
      (country_code: YupWhenValue) =>
        createPhoneNumberSchema(whenValue(country_code))
    ),
    organizer_type: Yup.string().required(t("COMMON.REQUIRED.FIELD")),
    internal_license_files: Yup.array().max(1).of(
      Yup.mixed<File>()
        .test("file-size", t("COMMON.FILE.TOO.LARGE"), (file) => !file || file.size <= 10 * 1024 * 1024)
        .test("file-type", t("COMMON.INVALID_FILE_TYPE"), (file) => !file || /\.(pdf|jpe?g|png|webp)$/i.test(file.name))
    ),
    documents: Yup.array().test(
      "fileSizeAndRequired",
      t("COMMON.FILE.TOO.LARGE"),
      function (files) {
        // Optional for تعليمي / حكومي / مجتمع; required for every other
        // type (`isLicenseUploadRequired`).
        const uploadOptional = !licenseUploadRequiredFor(
          orgTypeOptions,
          this.parent?.organizer_type
        );

        // When files are provided, always validate size
        if (files && files.length > 0) {
          return areDocumentsWithinSizeLimit(files);
        }

        // No new files provided
        if (uploadOptional) return true;

        // Non-Public: valid only if the user is still keeping at least one existing doc
        if (keptDocIds.length > 0) return true;

        return this.createError({ message: t("COMMON.REQUIRED.FIELD") });
      }
    ),
    nickname: Yup.string()
      .required(t("COMMON.REQUIRED.FIELD"))
      .max(50, t("COMMON.MUST.BE.ATMOST") + 50 + t("COMMON.CHARACTERS"))
      .matches(/^[A-Za-z0-9._]+$/, t("COMMON.ENGLISH_ONLY"))
      .test("nickname-availability", t("COMMON.USERNAME_TAKEN"), function () {
        if (
          !this.parent.nickname ||
          this.parent.nickname === initialNickname
        ) {
          return true;
        }
        return nicknameAvailable !== false;
      }),
    license_number: YupDigitsOnlyOptional(100).when("organizer_type", (type: YupWhenValue, schema: Yup.StringSchema) =>
      licenseNumberRequiredFor(orgTypeOptions, whenValue(type)) ? schema.required(t("COMMON.REQUIRED.FIELD")) : schema.notRequired()
    ),
    socialMedia: Yup.array().of(
      Yup.object()
        .shape({
          platform: Yup.string(),
          link: Yup.string().test(
            "url-format",
            t("COMMON.INVALID.URL"),
            function (value) {
              if (!value) return true;
              if (this.parent.platform === "whatsapp") {
                return value.trim().length <= 255 && YupWhatsAppContact.isValidSync(value);
              }
              return Yup.string().url().isValidSync(value);
            }
          ),
        })
        .test(
          "platform-link-dependency",
          "Platform and link must both be filled or both be empty",
          function (value) {
            const { platform, link } = value;
            if (!platform && !link) return true;
            if (!platform && link) {
              return this.createError({
                path: `${this.path}.platform`,
                message: t("COMMON.SOCIAL_MEDIA.PLATFORM_REQUIRED"),
              });
            }
            if (platform && !link) {
              return this.createError({
                path: `${this.path}.link`,
                message: t("COMMON.REQUIRED.FIELD"),
              });
            }
            const url = link && link.toLowerCase();
            const invalidUrl = () =>
              this.createError({
                path: `${this.path}.link`,
                message: t("COMMON.INVALID.URL_FORMAT"),
              });

            switch (platform) {
              case "facebook":
                if (url && !url.includes("facebook.com")) return invalidUrl();
                break;
              case "twitter":
                if (
                  url &&
                  !url.includes("twitter.com") &&
                  !url.includes("x.com")
                ) {
                  return invalidUrl();
                }
                break;
              case "whatsapp":
                if (url && !YupWhatsAppContact.isValidSync(url)) return invalidUrl();
                break;
              case "linkedin":
                if (url && !url.includes("linkedin.com")) return invalidUrl();
                break;
              case "instagram":
                if (url && !url.includes("instagram.com")) return invalidUrl();
                break;
              default:
                return true;
            }
            return true;
          }
        )
    ).test("one-contact-required", t("COMMON.ORGANIZATION_SOCIAL_REQUIRED"), rows => Boolean(rows?.some(row => row.platform && row.link?.trim()))),
  });
}
