import * as yup from "yup";
import { normalizeDatabaseDate } from "./dateUtils";

/**
 * Creates validation schema for the form
 * @param {boolean} isEditMode - Whether we're editing an existing guild (kept for API compatibility)
 */
// eslint-disable-next-line no-unused-vars
export const getValidationSchema = (isEditMode) =>
  yup.object({
    national_id: yup
      .string()
      .required("کد ملی الزامی است")
      .matches(/^[0-9]{10}$/, "کد ملی باید 10 رقم باشد"),
    mobile: yup
      .string()
      .required("شماره همراه الزامی است")
      .matches(/^[0-9]{11}$/, "شماره تلفن باید 11 رقم باشد"),
    first_name: yup.string(),
    last_name: yup.string(),
    guild_name: yup.string(),
    guild_category: yup.string(),
    city: yup.string(),
    address: yup.string(),
    license_expire_date: yup.string(),
    license_status: yup.string(),
    union_name: yup.string(),
    postal_code: yup.string(),
    guild_national_id: yup.string(),
    is_foreigner: yup.string(),
    national_code: yup.string(),
    has_steward: yup.string(),
    has_partner: yup.string(),
    license_number: yup.string(),
    isAccepted: yup
      .boolean()
      .test("req", "باید تعهد نامه را بپذیرید!", (val) => {
        return val === true;
      })
      .required("این فیلد اجباری است!"),
    guilds: yup
      .array()
      .min(1, "حداقل یک واحد صنفی باید وجود داشته باشد")
      .of(
        yup
          .object({
            license_number: yup.string().required("شماره مجوز الزامی است"),

            steward: yup.boolean(),
            guild: yup.boolean(),
          })
          .test(
            "steward-guild-required",
            "برای هر واحد صنفی، حداقل یکی از گزینه‌های مباشر یا صنف باید انتخاب شود",
            (value) => value?.steward === true || value?.guild === true
          )
      ),
  });

/**
 * Extracts initial form values from guild data for edit mode
 *
 * Data source: Guild data passed directly when editing existing guild
 * This is used when the component receives a guild prop (edit mode)
 *
 * @param {Object} guildDataForEdit - Guild data object from our database (edit mode)
 * @returns {Object} Initial form values for Formik
 */
export const getInitialValues = (guildDataForEdit) => {
  // Extract user data from edit mode guild object
  const userDataFromEdit = guildDataForEdit?.user || {};
  const addressDataFromEdit = guildDataForEdit?.address || {};
  const cityDataFromEdit = addressDataFromEdit?.city || {};

  return {
    // Personal Information Fields (from user object in edit mode)
    first_name: userDataFromEdit.firstName || "",
    last_name: userDataFromEdit.lastName || "",
    national_id: userDataFromEdit.nationalId || "",
    national_code: userDataFromEdit.nationalCode || "",
    birth_date: normalizeDatabaseDate(userDataFromEdit.birthday || ""),
    father_name: userDataFromEdit.fatherName || "",
    gender: userDataFromEdit.gender || "",
    person_city: userDataFromEdit.city || cityDataFromEdit?.name || "",
    city: cityDataFromEdit?.id ?? cityDataFromEdit?.key ?? "",
    is_alive:
      userDataFromEdit.isAlive === true || userDataFromEdit.is_alive === true
        ? "بلی"
        : userDataFromEdit.isAlive === false ||
          userDataFromEdit.is_alive === false
        ? "خیر"
        : "",
    mobile: userDataFromEdit.mobile || "",

    // Guild Information Fields (from guild object in edit mode)
    guild_name: guildDataForEdit?.guildsName || guildDataForEdit?.name || "",
    area_activity: guildDataForEdit?.areaActivity || "",
    city_name: cityDataFromEdit.name || "",
    address: addressDataFromEdit.address || "",
    license_expire_date: normalizeDatabaseDate(
      guildDataForEdit?.licenseExpireDate || ""
    ),
    license_status: guildDataForEdit?.licenseStatus || "",
    license_type: guildDataForEdit?.licenseType || "",
    union_name: guildDataForEdit?.unionName || "",
    postal_code: addressDataFromEdit.postalCode || "",
    phone_number: guildDataForEdit?.phoneNumber || "",
    license_number:
      guildDataForEdit?.license_number ?? guildDataForEdit?.licenseNumber ?? "",
    // شناسه ملی شرکت: from company_identifier when dbRegister true
    guild_national_id:
      guildDataForEdit?.company_identifier ??
      guildDataForEdit?.companyIdentifier ??
      guildDataForEdit?.nationalCode ??
      guildDataForEdit?.nationalId ??
      "",
    corporation_name: guildDataForEdit?.companyName || "",
    license_issue_date: normalizeDatabaseDate(
      guildDataForEdit?.licenseIssueDate || ""
    ),

    // Status Fields (from guild object in edit mode)
    is_foreigner:
      guildDataForEdit?.isForeignNational === true
        ? "بلی"
        : guildDataForEdit?.isForeignNational === false
        ? "خیر"
        : "",
    has_steward: guildDataForEdit?.hasSteward || "",
    has_partner: guildDataForEdit?.hasPartner || "",
    steward:
      typeof guildDataForEdit?.steward === "boolean"
        ? guildDataForEdit.steward
        : typeof guildDataForEdit?.isSteward === "boolean"
        ? guildDataForEdit.isSteward
        : false,
    guild:
      typeof guildDataForEdit?.guild === "boolean"
        ? guildDataForEdit.guild
        : typeof guildDataForEdit?.isGuild === "boolean"
        ? guildDataForEdit.isGuild
        : false,
    verify_mobile: guildDataForEdit?.verifyMobile || false,
    active: guildDataForEdit?.active ?? null,
    isAccepted: guildDataForEdit?.provinceAcceptState === "accepted" || false,

    // Additional Edit Mode Fields
    company_name: guildDataForEdit?.companyName || "",
    company_identifier: guildDataForEdit?.companyIdentifier || "",
    type_activity_name: guildDataForEdit?.typeActivityName || "",

    // Guilds array for validation (edit mode) – must include license_number for schema
    guilds: guildDataForEdit
      ? [
          {
            steward:
              typeof guildDataForEdit?.steward === "boolean"
                ? guildDataForEdit.steward
                : typeof guildDataForEdit?.isSteward === "boolean"
                ? guildDataForEdit.isSteward
                : false,
            guild:
              typeof guildDataForEdit?.guild === "boolean"
                ? guildDataForEdit.guild
                : typeof guildDataForEdit?.isGuild === "boolean"
                ? guildDataForEdit.isGuild
                : false,
            license_number:
              guildDataForEdit?.license_number ??
              guildDataForEdit?.licenseNumber ??
              "",
          },
        ]
      : [],
  };
};
