import { getRoleFromUrl } from "../../../../../utils/getRoleFromUrl";
import { normalizeExternalApiDate, normalizeDatabaseDate } from "./dateUtils";
import { formatDateForSubmit } from "./dateUtils";

/**
 *
 * @param {Object} values - Form values from Formik
 * @param {Object} guild - Guild data when editing existing guild (edit mode)
 * @param {string} originalPhoneNumber - Original phone number before edit
 * @param {boolean} hasInquiry - Whether data came from external API inquiry (true) or database (false)
 */
export const prepareSubmitData = (
  values,
  guild,
  originalPhoneNumber,
  hasInquiry
) => {
  const baseData = {
    national_id: values.national_id,
    mobile: values.mobile,
    mobilenumber: values.mobile,
    steward: !!values.steward,
    guild: !!values.guild,
    active_register_code: !!values.verify_mobile,
    firstName: values.first_name || "",
    lastName: values.last_name || "",
    fatherName: values.father_name || "",
    gender: values.gender || "",
    identityNo: values.national_code || "",
    isLive: values.is_alive === "بلی" || values.is_alive === true,
    birthDate: formatDateForSubmit(
      values.birth_date || "",
      hasInquiry === true
    ),
    city: values.person_city || "",
    city_name: values.city_name || "",
    address: values.address || "",
    postalcode: values.postal_code || "",
    licenseNumber: values.license_number || "",
    licenseExpireDate: formatDateForSubmit(
      values.license_expire_date || "",
      hasInquiry === true
    ),
    licenseIssueDate: formatDateForSubmit(
      values.license_issue_date || "",
      hasInquiry === true
    ),
    licenseType: values.license_type || "",
    licenseStatus: values.license_status || "",
    isicname: values.area_activity || "",
    corporationName: values.corporation_name || "",
    nationalId: values.guild_national_id || "",
    unionName: values.union_name || "",
    phonenumber: values.phone_number || "",
    hasPartner: values.has_partner === true || values.has_partner === "بلی",
    isForeigner: values.is_foreigner === true || values.is_foreigner === "بلی",
    title: values.guild_name || "",
    role: getRoleFromUrl(),
    has_inquiry: hasInquiry !== null ? hasInquiry : false,
    ...(values.active !== null && { active: values.active }),
  };

  if (guild) {
    baseData.guilds_key = guild.key;
    if (values.mobile !== originalPhoneNumber) {
      baseData.mobile = values.mobile;
      baseData.mobilenumber = values.mobile;
    }
  }

  return baseData;
};

const extractFormFieldsFromDatabaseInquiry = (
  responseDataFromDb,
  inquiryNationalCode
) => {
  const userFromDb = responseDataFromDb.user || {};
  const firstGuildFromDb =
    Array.isArray(responseDataFromDb.guilds) &&
    responseDataFromDb.guilds.length > 0
      ? responseDataFromDb.guilds[0]
      : {};
  const addressFromDb = firstGuildFromDb?.address || {};

  return {
    // Personal Information Fields
    first_name: userFromDb.firstName || "",
    last_name: userFromDb.lastName || "",
    national_id: String(userFromDb.nationalId || inquiryNationalCode).trim(),
    national_code: userFromDb.nationalCode || "",
    birth_date: normalizeDatabaseDate(userFromDb.birthday || ""),
    father_name: userFromDb.fatherName || "",
    gender: userFromDb.gender || "",

    person_city: userFromDb.city || "",
    city: "",
    is_alive:
      userFromDb.isAlive === false
        ? "خیر"
        : userFromDb.isAlive === true
        ? "بلی"
        : "",
    mobile: userFromDb.mobile || "",

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

    // Status Fields (is_foreign_national is at guild level in API response)
    is_foreigner:
      firstGuildFromDb.isForeignNational === true
        ? "بلی"
        : firstGuildFromDb.isForeignNational === false
        ? "خیر"
        : "",
    has_steward:
      responseDataFromDb.steward === false
        ? false
        : responseDataFromDb.steward === true
        ? true
        : "",
    has_partner:
      responseDataFromDb.hasPartner === false
        ? false
        : responseDataFromDb.hasPartner === true
        ? true
        : "",
    steward: firstGuildFromDb.isSteward || false,
    guild:
      typeof firstGuildFromDb.guild === "boolean"
        ? firstGuildFromDb.guild
        : false,

    // Additional Database Fields
    company_name: firstGuildFromDb.companyName || "",
    company_identifier: firstGuildFromDb.companyIdentifier || "",
    type_activity_name: firstGuildFromDb.typeActivity || "",
  };
};

/**
 * Personal info only from external API (dbRegister false).
 * Guild data is mapped per guild via mapExternalApiGuildToFormValues.
 */
const extractFormFieldsFromExternalApi = (
  responseDataFromExternalApi,
  inquiryNationalCode
) => {
  const userFromExternalApi = responseDataFromExternalApi.user || {};
  const firstGuild =
    Array.isArray(responseDataFromExternalApi.guilds) &&
    responseDataFromExternalApi.guilds.length > 0
      ? responseDataFromExternalApi.guilds[0]
      : {};
  const layerTwo = firstGuild.layerTwo || {};

  return {
    first_name: userFromExternalApi.firstName || "",
    last_name: userFromExternalApi.lastName || "",
    national_id: String(
      layerTwo.nationalcode ||
        userFromExternalApi.nationalCode ||
        inquiryNationalCode
    ).trim(),
    national_code: userFromExternalApi.identityNo || "",
    birth_date: normalizeExternalApiDate(userFromExternalApi.birthDate || ""),
    father_name: userFromExternalApi.fatherName || "",
    gender:
      userFromExternalApi.gender === true
        ? "True"
        : userFromExternalApi.gender === false
        ? "False"
        : "",
    person_city: userFromExternalApi.city || "",
    city: "",
    is_alive:
      userFromExternalApi.isLive === true
        ? "بلی"
        : userFromExternalApi.isLive === false
        ? "خیر"
        : "",
    mobile: layerTwo.mobilenumber || "",
  };
};

/**
 * Maps one external API guild (dbRegister false) to guild form values.
 * All fields are guild data, not personal info.
 */
export const mapExternalApiGuildToFormValues = (guild) => {
  const layerTwo = guild?.layerTwo || {};
  return {
    guild_name: guild?.title || "",
    area_activity: guild?.isicname || "",
    city_name: guild?.city || "",
    address: guild?.address || "",
    license_expire_date: normalizeExternalApiDate(
      guild?.licenseExpireDate || ""
    ),
    license_status: guild?.licenseStatus || "",
    license_type: guild?.licenseType || "",
    license_number: guild?.licenseNumber || "",
    license_issue_date: normalizeExternalApiDate(
      layerTwo.licenseIssueDate || ""
    ),
    union_name: layerTwo.unionName || "",
    postal_code: layerTwo.postalcode || "",
    phone_number: layerTwo.phonenumber || "",
    guild_national_id: layerTwo.nationalId || "",
    corporation_name: layerTwo.corporationName || "",
    active: guild?.active ?? true,
    is_foreigner:
      layerTwo.isForeigner === "خیر"
        ? false
        : layerTwo.isForeigner === "بلی"
        ? true
        : false,
    has_steward:
      layerTwo.hasSteward === "خیر"
        ? false
        : layerTwo.hasSteward === "بلی"
        ? true
        : false,
    has_partner:
      layerTwo.hasPartner === "خیر"
        ? false
        : layerTwo.hasPartner === "بلی"
        ? true
        : false,
    steward:
      layerTwo.hasSteward === "خیر"
        ? false
        : layerTwo.hasSteward === "بلی"
        ? true
        : false,
    guild:
      layerTwo.hasSteward === "خیر"
        ? true
        : layerTwo.hasSteward === "بلی"
        ? true
        : true,
  };
};

export const mapResponseDataToFormFields = (
  responseData,
  inquiryNationalCode,
  formik
) => {
  const isFromExternalApi = responseData.dbRegister === false;

  // Route to appropriate extractor based on data source
  const formFieldValues = isFromExternalApi
    ? extractFormFieldsFromExternalApi(responseData, inquiryNationalCode)
    : extractFormFieldsFromDatabaseInquiry(responseData, inquiryNationalCode);

  formik.setValues({ ...formik.values, ...formFieldValues });
};
