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

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.city || "",
    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;
};

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

  // New structure: user is at top level, guilds is an array
  const userData = responseData.user || {};
  // For personal info, we use the first guild's data if available, or empty
  const firstGuild =
    Array.isArray(responseData.guilds) && responseData.guilds.length > 0
      ? responseData.guilds[0]
      : {};
  const guildData = firstGuild || {};
  const layerTwo = guildData.layerTwo || {};
  const addressData = firstGuild?.address || guildData.address || {};
  const provinceData = addressData.province || {};
  const cityData = addressData.city || {};

  const nationalIdValue = isExternalApi
    ? String(
        layerTwo.nationalcode || userData.nationalCode || inquiryNationalCode
      ).trim()
    : String(userData.nationalId || inquiryNationalCode).trim();

  const birthDatePersian = isExternalApi
    ? normalizeExternalApiDate(userData.birthDate || "")
    : normalizeDatabaseDate(userData.birthday || "");

  const licenseExpireDatePersian = isExternalApi
    ? normalizeExternalApiDate(guildData.licenseExpireDate || "")
    : normalizeDatabaseDate(firstGuild.licenseExpireDate || "");

  const licenseIssueDatePersian = isExternalApi
    ? normalizeExternalApiDate(layerTwo.licenseIssueDate || "")
    : normalizeDatabaseDate(responseData.licenseIssueDate || "");

  const genderValue = isExternalApi
    ? userData.gender === true
      ? "True"
      : userData.gender === false
      ? "False"
      : ""
    : userData.gender || "";

  const isAliveValue = isExternalApi
    ? userData.isLive === true
      ? "بلی"
      : userData.isLive === false
      ? "خیر"
      : ""
    : userData.isAlive === false
    ? "خیر"
    : userData.isAlive === true
    ? "بلی"
    : "";

  const isForeignerValue = isExternalApi
    ? layerTwo.isForeigner === "خیر"
      ? false
      : layerTwo.isForeigner === "بلی"
      ? true
      : ""
    : responseData.isForeignNational === false
    ? false
    : responseData.isForeignNational === true
    ? true
    : "";

  const hasStewardValue = isExternalApi
    ? layerTwo.hasSteward === "خیر"
      ? false
      : layerTwo.hasSteward === "بلی"
      ? true
      : ""
    : responseData.steward === false
    ? false
    : responseData.steward === true
    ? true
    : "";

  const hasPartnerValue = isExternalApi
    ? layerTwo.hasPartner === "خیر"
      ? false
      : layerTwo.hasPartner === "بلی"
      ? true
      : ""
    : responseData.hasPartner === false
    ? false
    : responseData.hasPartner === true
    ? true
    : "";

  const values = {
    first_name: userData.firstName || "",
    last_name: userData.lastName || "",
    national_id: nationalIdValue,
    national_code: isExternalApi
      ? userData.identityNo || ""
      : userData.nationalCode || "",
    birth_date: birthDatePersian,
    father_name: userData.fatherName || "",
    gender: genderValue,
    person_city: userData.city || "",
    is_alive: isAliveValue,
    // Guild fields - will be set per guild in accordion, so we set empty or first guild's data
    guild_name: isExternalApi
      ? guildData.title || ""
      : firstGuild.guildsName || "",
    area_activity: isExternalApi
      ? guildData.isicname || ""
      : firstGuild.areaActivity || "",
    state: isExternalApi ? guildData.state || "" : provinceData.name || "",
    city: isExternalApi ? guildData.city || "" : cityData.name || "",
    address: isExternalApi
      ? guildData.address || ""
      : addressData.address || "",
    license_expire_date: licenseExpireDatePersian,
    license_status: isExternalApi
      ? guildData.licenseStatus || ""
      : firstGuild.licenseStatus || "",
    license_type: isExternalApi
      ? guildData.licenseType || ""
      : firstGuild.licenseType || "",
    license_number: isExternalApi
      ? guildData.licenseNumber || ""
      : firstGuild.licenseNumber || "",
    union_name: isExternalApi
      ? layerTwo.unionName || ""
      : firstGuild.unionName || "",
    postal_code: isExternalApi
      ? layerTwo.postalcode || ""
      : addressData.postalCode || "",
    phone_number: isExternalApi
      ? layerTwo.phonenumber || ""
      : firstGuild.phoneNumber || "",
    mobile: isExternalApi ? layerTwo.mobilenumber || "" : userData.mobile || "",
    guild_national_id: isExternalApi
      ? layerTwo.nationalId || ""
      : firstGuild.nationalCode || "",
    is_foreigner: isForeignerValue,
    corporation_name: isExternalApi
      ? layerTwo.corporationName || ""
      : firstGuild.companyName || "",
    has_steward: hasStewardValue,
    has_partner: hasPartnerValue,
    steward: isExternalApi ? false : firstGuild.isSteward || false,
    guild: isExternalApi
      ? typeof guildData.guild === "boolean"
        ? guildData.guild
        : false
      : typeof firstGuild.guild === "boolean"
      ? firstGuild.guild
      : false,
    license_issue_date: licenseIssueDatePersian,
    ...(isExternalApi
      ? {}
      : {
          company_name: firstGuild.companyName || "",
          company_identifier: firstGuild.companyIdentifier || "",
          type_activity_name: firstGuild.typeActivity || "",
        }),
  };

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