hi refactor this code file to better  convert to functions etc and simplfily the code 
import { GenericAny, MdmsAccountDetail, bankApi, mdmsAccountApi } from '@admin-webcomponents/sdk';
import { Logger } from '@nextgen-web-framework/core';
import { cloneDeep } from 'lodash';
import { type Data, type DropDownDataInterface } from '@nextgen-web-framework/all';
import { MdmsCountryState } from '@admin-webcomponents/sdk/services/models/models/MdmsCountryState';
import { EditFieldType } from '../components/DynamicForm/types/enums';
import { ApiDropDownKey, FormAPIKey } from '../components/DynamicFormEditableWrapper/types/enum';
import { DynamicForm, DynamicField } from '../components/UserDetailsContainer/types/propTypes';
import { portalCodeFromCity, portalCodeFromColony, postalCodeFromParish } from './constants';

/* eslint-disable  @typescript-eslint/no-explicit-any */
type ApiResponse = MdmsAccountDetail & { accountMst?: { [key: string]: any } };
export type DropdownData = Record<string, any>;

const loggerInstance = Logger.getInstance();
const API_VERSION_V1 = 'v1';

export interface DynamicFormComponent {
  componentType: 'DynamicFormComponent';
  dynamicFormsData: DynamicForm[];
  footerButtonProps?: FooterButton[];
  apiKey?: string;
}

interface CardFieldConfig extends DynamicField {
  subMasterKey?: string;
}

interface CardFormData {
  layoutColumns: number;
  masterKey: string;
  subMasterKey: string;
  title: Record<string, string>;
  fields: CardFieldConfig[];
}

interface CardFormComponent {
  componentType: 'CardIdContainer';
  cardContainerData: CardFormData[];
  footerButtonProps?: FooterButton[];
  apiKey?: string;
}

interface FooterButton {
  isVisible: boolean;
  label: string;
  theme: string;
  buttonKey: string | Record<string, string>;
}

interface BankRespose {
  banks: [
    {
      bankId: string;
      bankName: string;
      actFlag: string;
    },
  ];
}
interface BankBranchRespose {
  branches: [
    {
      branchId: string;
      branchName: string;
      actFlag: string;
    },
  ];
}
export type ComponentConfig = DynamicFormComponent | CardFormComponent;

const resolveValue = (path: string | undefined, data: any): any =>
  path?.split('.').reduce((acc, key) => (acc && key && acc[key] ? acc[key] : null), data);

const setDropdownData = (apiResponse: ApiResponse, field: DynamicField, dropdownData: DropdownData) => {
  let data = field?.editVariantProps?.dataKey ? dropdownData?.[field?.editVariantProps.dataKey] : undefined;

  if (field?.parentDependentKey && field?.editVariantProps?.dataKey) {
    const parentResolvedVal = resolveValue(field?.parentDependentKey, apiResponse);
    // Use the resolved parent value to fetch the dependent data
    data = data?.[parentResolvedVal];
  }
  // Handle country-based fallback for data if needed
  data = Array.isArray(data) ? (data as Data[]) : data?.[apiResponse.accountMst?.cntryCd];
  let resolvedValue = resolveValue(field?.actualKey ?? field?.masterKey, apiResponse);
  let filteredData = data?.filter((item: Data) => item.id === resolvedValue || item.title === resolvedValue)?.[0];
  if (
    field.editVariantProps?.defaultSelectedDropDownDependencyKey &&
    field.editVariantProps.defaultSelectedDropDownOptionList
  ) {
    const resolvedValue = resolveValue(field.editVariantProps.defaultSelectedDropDownDependencyKey, apiResponse);
    field.editVariantProps.defaultSelectedDropDownOption = field.editVariantProps.selectedDropdownOption =
      field.editVariantProps.defaultSelectedDropDownOptionList[resolvedValue];

    field.defaultFixedValue = field.editVariantProps.selectedDropdownOption.id as string;
  }
  if (field.editVariantProps?.fieldType === EditFieldType.DROPDOWN_INPUT && resolvedValue) {
    const value = resolvedValue.split(' ');
    const temp = value.shift();
    field.dropdownInputValue = value.join(' ');
    resolvedValue = temp;
    filteredData = data?.filter((item: Data) => item.id === resolvedValue || item.title === resolvedValue)?.[0];
  }

  return [resolvedValue, data, filteredData];
};

const specialtranformationHandling = (config: ComponentConfig, formData: DynamicForm, field: DynamicField) => {
  if (
    [FormAPIKey.MAILING_ADDRESS_EDIT, FormAPIKey.SHIPPING_ADDRESS_EDIT, FormAPIKey.UPDATE_PHONE_NUMBER].includes(
      config.apiKey as FormAPIKey,
    )
  ) {
    const parentDependentField = formData.fields?.find((ifield) => ifield.masterKey === field.parentDependentKey);
    if (parentDependentField && parentDependentField.value) {
      field.isDependentVisible = true;
      if (
        field.dependencyVisibilityList &&
        !field.dependencyVisibilityList.includes(parentDependentField.value as string)
      ) {
        field.isDependentVisible = false;
      }
    }
  }
};

export const transformConfigWithDataForEditable = (
  apiResponse: ApiResponse,
  config: ComponentConfig,
  dropdownData: DropdownData = {},
): ComponentConfig => {
  if (config.componentType === 'DynamicFormComponent') {
    const dynamicConfig = cloneDeep(config);

    dynamicConfig.dynamicFormsData = dynamicConfig.dynamicFormsData.map((formData) => ({
      ...formData,
      fields: formData.fields?.map((field) => {
        const [resolvedValue, data, filteredData] = setDropdownData(apiResponse, field, dropdownData);

        return {
          ...field,
          value: field.defaultFixedValue ?? resolvedValue,
          editVariantProps: {
            ...field.editVariantProps,
            fieldType: field.editVariantProps?.fieldType as EditFieldType,
            dropdownData: data,
            inputValidations: field.editVariantProps?.inputValidations,
            inputType: field.editVariantProps?.inputType,
            isDisabled: field.editVariantProps?.isDisabled,
            selectedDropdownOption: filteredData,
          },
        };
      }),
    }));
    dynamicConfig.dynamicFormsData = dynamicConfig.dynamicFormsData.map((formData) => ({
      ...formData,
      fields: formData.fields?.map((field) => {
        setFieldTypesAndSibling(field, formData.fields);
        setRequiredFiledsBasedOnParent(field, formData.fields);
        setPrefixDependancy(field, formData.fields);

        const [resolvedValue, _, filteredData] = setDropdownData(apiResponse, field, dropdownData);
        specialtranformationHandling(config, formData, field);

        return {
          ...field,
          value: field.defaultFixedValue ?? resolvedValue,
          editVariantProps: {
            ...field.editVariantProps,
            fieldType: field.editVariantProps?.fieldType as EditFieldType,
            selectedDropdownOption: field.editVariantProps?.defaultSelectedDropDownOption ?? filteredData,
          },
        };
      }),
    }));
    return dynamicConfig;
  }

  //Commenting below code as we don;t have CardContainer for now
  //but we can use it in future if required

  // if (config.componentType === 'CardIdContainer') {
  //   const cardConfig = config as CardFormComponent;

  //   cardConfig.cardContainerData = cardConfig.cardContainerData.map((cardData) => {
  //     const masterData = resolveValue(cardData.masterKey, apiResponse) || [];
  //     const filteredData = Array.isArray(masterData)
  //       ? masterData.filter((item) => item[cardData.subMasterKey] === cardData.subMasterKey)
  //       : [];

  //     return {
  //       ...cardData,
  //       fields: cardData.fields.map((field) => ({
  //         ...field,
  //         selectedDropdownOption: filteredData.map((item) => resolveValue(field.masterKey, item)),
  //         dropdownData:
  //           field.editVariantProps?.fieldType === 'dropdown' && field.editVariantProps.dataKey
  //             ? dropdownData[field.editVariantProps.dataKey] || []
  //             : undefined,
  //       })),
  //     };
  //   });
  //   return cardConfig;
  // }

  return config;
};

export const transformAPIdropDownData = async (
  version: string,
  editVariantProps: GenericAny,
  args: string[],
  formApiKey: string,
  apiResponse?: ApiResponse,
) => {
  loggerInstance.log(args);
  switch (editVariantProps.dataKey) {
    case ApiDropDownKey.BANK_NAME: {
      try {
        const response = (await bankApi.fetchBank(version, args[0])) as unknown as BankRespose;
        return response?.banks.map((bank) => ({
          id: bank.bankId,
          title: bank.bankName,
        }));
      } catch (err) {
        return [];
      }
    }
    case ApiDropDownKey.BANK_BRANCH_NAME: {
      try {
        const response = (await bankApi.fetchBankBranch(
          version,
          getArgsForBankBranchDropdown(args, formApiKey, apiResponse?.accountMst?.cntryCd as string),
        )) as unknown as BankBranchRespose;
        return response?.branches.map((branch) => ({
          id: branch.branchId,
          title: branch.branchName,
        }));
      } catch (err) {
        return [];
      }
    }
    case ApiDropDownKey.ADDRESS_STATE: {
      try {
        const response = (await mdmsAccountApi.getStates(args[0])) as unknown as MdmsCountryState;
        return response?.states?.map((state) => ({
          id: state.stateCd,
          title: state.stateNm,
        }));
      } catch (err) {
        return [];
      }
    }
    case ApiDropDownKey.ADDRESS_CITY: {
      try {
        const [country, stateId] = args;
        const response = await mdmsAccountApi.getLocalities(country, { locality1Cd: stateId });

        editVariantProps.hiddendata = generatePostalData(
          portalCodeFromCity,
          country,
          response.localities,
          'localityCd',
          'fromPostalCd',
          'toPostalCd',
        );

        return response.localities.map((locality: any) => ({
          id: locality.localityCd,
          title: locality.localityNm,
        }));
      } catch (err) {
        return [];
      }
    }
    case ApiDropDownKey.ADDRESS_DISTRICT: {
      try {
        const [country, stateId, cityId] = args;
        const response = await mdmsAccountApi.getLocalities(country, {
          locality1Cd: stateId,
          locality2Cd: cityId,
        });
        return response.localities.map((locality: any) => ({
          id: locality.localityCd,
          title: locality.localityNm,
        }));
      } catch (err) {
        return [];
      }
    }
    case ApiDropDownKey.ADDRESS_PARISH: {
      try {
        const [country, stateId, cityId, districtId] = args;
        const response = await mdmsAccountApi.getLocalities(country, {
          locality1Cd: stateId,
          locality2Cd: cityId,
          locality3Cd: districtId,
        });
        return response.localities.map((locality: any) => ({
          id: locality.localityCd,
          title: locality.localityNm,
        }));
      } catch (err) {
        return [];
      }
    }
    default:
      return [];
  }
};

export const getArgsForBankBranchDropdown = (args: string[], formApiKey: string, cntryCd: string): string[] => {
  if (args.length === 1) {
    return [
      ...args,
      formApiKey === FormAPIKey.BANK_ACCOUNT_ADD_BONUS_REMITTANCE ||
      formApiKey === FormAPIKey.BANK_ACCOUNT_EDIT_BONUS_REMITTANCE
        ? cntryCd
        : 'VE',
    ];
  } else {
    return [...args];
  }
};
const setFieldTypesAndSibling = (val: DynamicField, resetFieldValues: DynamicField[] | undefined) => {
  if (val.fieldTypeDependentOn && val.dependentFiledType) {
    const parentDependentField = resetFieldValues?.find((field) => field.masterKey === val.fieldTypeDependentOn);

    val.editVariantProps &&
      (val.editVariantProps.fieldType = val.dependentFiledType[parentDependentField?.value as string] as EditFieldType);
  }
  if (val.selectedSiblingOnParentKey) {
    const parentDependentField = resetFieldValues?.find((field) => field.masterKey === val.parentDependentKey);
    val.siblingDependency = val.selectedSiblingOnParentKey[parentDependentField?.value as string];
  }
  if (val.labelDependentKey && val.labelList) {
    const parentDependentField = resetFieldValues?.find((field) => field.masterKey === val.labelDependentKey);
    val.label = val.labelList[parentDependentField?.value as string];
  }
};

const setRequiredFiledsBasedOnParent = (val: DynamicField, resetFieldValues: DynamicField[] | undefined) => {
  if (val.editVariantProps?.inputValidations?.requiredDependencyList) {
    const parentDependentValue = resetFieldValues?.find(
      (field) => field.masterKey === val.editVariantProps?.inputValidations?.dependentParentKey,
    );
    if (val.editVariantProps.inputValidations.requiredDependencyList.includes(parentDependentValue?.value as string)) {
      val.editVariantProps.inputValidations.isRequired = true;
    } else {
      val.editVariantProps.inputValidations.isRequired = false;
    }
  }
};

const setPrefixDependancy = (field: DynamicField, fields: DynamicField[] | undefined) => {
  if (field.prefixDependentKey && field.prefixDependancyMapper) {
    const prefixDependentField = fields?.find((ifield) => ifield.masterKey === field.prefixDependentKey);
    if (prefixDependentField) {
      if (Object.keys(field.prefixDependancyMapper).includes(prefixDependentField.value as string)) {
        field.value = field.prefixDependancyMapper[prefixDependentField.value as string];
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        field.editVariantProps!.isDisabled = true;
      } else {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        field.editVariantProps!.isDisabled = false;
      }
    }
  }
};

const siblingDependencyHandler = (resetFieldValues: DynamicField[], val: DynamicField, fieldIndex: number) => {
  const parentDependentField = resetFieldValues.find((field) => field.masterKey === val.parentDependentKey);
  if (
    val.dependencyVisibilityList &&
    parentDependentField &&
    !val.dependencyVisibilityList.includes(parentDependentField.value as string)
  ) {
    val.isDependentVisible = false;
  }
  if (val.siblingDependency === resetFieldValues?.[fieldIndex].masterKey) {
    val.editVariantProps && (val.editVariantProps.isDisabled = false);
  } else {
    val.editVariantProps && (val.editVariantProps.isDisabled = true);

    return false;
  }
  return true;
};

export const handleDependentDataAction = async (
  prevValue: DynamicField[],
  fieldIndex: number,
  apiResponse: ApiResponse,
  dropdownData: DropdownData = {},
  id = '',
  formApiKey?: string,
) => {
  // Filter and update field values
  const resetFieldValues = handleResetDependentData(
    prevValue,
    prevValue[fieldIndex].isNestedDependentVisible,
    fieldIndex,
  );

  const modifiedPrevValue = await Promise.all(
    resetFieldValues?.map(async (val) => {
      setFieldTypesAndSibling(val, resetFieldValues);
      setRequiredFiledsBasedOnParent(val, resetFieldValues);
      if (
        val.parentDependentKey === resetFieldValues?.[fieldIndex].masterKey ||
        val.siblingDependency === resetFieldValues?.[fieldIndex].masterKey
      ) {
        val.isDependentVisible = true;
        if (val.siblingDependency) {
          const proceed = siblingDependencyHandler(resetFieldValues, val, fieldIndex);
          if (!proceed) {
            return val;
          }
        }
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        val.editVariantProps!.isDisabled = false;
        if (
          !val.siblingDependency &&
          val.dependencyVisibilityList &&
          !val.dependencyVisibilityList.includes(
            resetFieldValues?.[fieldIndex].editVariantProps?.selectedDropdownOption?.id as unknown as string,
          )
        ) {
          val.isDependentVisible = false;
        }
        val.value = val.defaultFixedValue ?? '';
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        val.editVariantProps!.error = '';

        if (
          [EditFieldType.DROPDOWN, EditFieldType.DROPDOWN_INPUT].includes(
            val.editVariantProps?.fieldType as EditFieldType,
          )
        ) {
          await setDropdownValue(val.editVariantProps, resetFieldValues, apiResponse, id, dropdownData, formApiKey);
        }
        setPrefixDependancy(val, resetFieldValues);
      }

      return val;
    }) || [],
  );
  return modifiedPrevValue;
};

const setDropdownValue = async (
  editVariantProps: GenericAny,
  resetFieldValues: DynamicField[],
  apiResponse: ApiResponse,
  id: string,
  dropdownData: DropdownData = {},
  formApiKey?: string,
) => {
  if (editVariantProps.fetchFromAPI) {
    const paramKeys = editVariantProps.parentParamsKey || [];
    const params = resetFieldValues
      .filter((field) => paramKeys.indexOf(field.masterKey || '') > -1)
      .map((element) => element.editVariantProps?.selectedDropdownOption?.id);

    const dropdownData = await transformAPIdropDownData(
      API_VERSION_V1,
      editVariantProps,
      params as unknown as string[],
      formApiKey as string,
      apiResponse,
    );
    editVariantProps.dropdownData = dropdownData;
  } else {
    const dropdownDataKey = dropdownData?.[editVariantProps.dataKey];
    const tdropdownData = Array.isArray(dropdownDataKey) ? dropdownDataKey : dropdownDataKey?.[id];
    editVariantProps.dropdownData = tdropdownData;
  }
};

export const handleResetDependentData = (
  prevValue: DynamicField[],
  nestedDependent: boolean | undefined,
  fieldIndex: number,
): DynamicField[] => {
  const resetChildrenDepenedencyList = prevValue[fieldIndex].resetChildrenDepenedencyList ?? [];
  resetChildrenDepenedencyList.forEach((resetKey) => {
    const childIndex = prevValue.findIndex((field) => field.masterKey === resetKey);
    if (childIndex > -1) {
      const childField = prevValue[childIndex];
      childField.value = childField.defaultFixedValue ?? '';
      childField.dropdownInputValue = '';
      if (
        childField.editVariantProps?.fieldType === EditFieldType.DROPDOWN ||
        childField.editVariantProps?.fieldType === EditFieldType.DROPDOWN_INPUT
      ) {
        childField.editVariantProps.dropdownData = [];
        childField.editVariantProps.selectedDropdownOption = childField.editVariantProps
          .defaultSelectedDropDownOption ?? { id: '', title: '' };
      }

      if (nestedDependent && childField.editVariantProps?.fieldType) {
        childField.isDependentVisible = true;
        childField.editVariantProps.isDisabled = true;
      }
    }
  });
  return prevValue;
};

const setValue = (path: string, value: any, data: any): void => {
  const keys = path.split('.');
  let current = data;
  keys.forEach((key, index) => {
    if (index === keys.length - 1) {
      current[key] = value;
    } else {
      if (!current[key]) {
        current[key] = {};
      }
      current = current[key];
    }
  });
};

export const updateApiData = (formData: any, apiData: any): any => {
  formData.fields?.forEach((field: any) => {
    if (field.masterKey && field.value !== undefined) {
      let { value } = field;
      if (field.dropdownInputValue) {
        value += ` ${field.dropdownInputValue}`;
      }
      let key = field.masterKey;
      if (field.actualKey && field.editVariantProps.fieldType) {
        key = field.actualKey;
      }
      setValue(key, value, apiData);
    }
  });
  return apiData;
};

export const handleDropdownOption = async (
  fields: DynamicField[],
  fieldIndex: number,
  selectedOption: string | DropDownDataInterface,
  apiResponse: ApiResponse,
  handleLoader: (value: boolean) => void,
  dropdownData: DropdownData = {},
  formApiKey?: string,
) => {
  const dropdown = selectedOption as Data;
  fields[fieldIndex].value = dropdown.id as string;

  if (fields[fieldIndex]?.editVariantProps) {
    fields[fieldIndex].editVariantProps = {
      ...fields[fieldIndex].editVariantProps,
      selectedDropdownOption: dropdown,
    };
  }

  handleLoader(true);
  await handleDependentDataAction(fields, fieldIndex, apiResponse, dropdownData, dropdown?.id as string, formApiKey);
  handleLoader(false);
};

export const initialdropDownValuesGenerator = (
  modifiedFormDataFields: DynamicField[],
  apiVersion: string,
  searchAccountUserDetails: GenericAny,
  formApiKey: string | undefined,
): GenericAny =>
  Promise.all(
    modifiedFormDataFields?.map(async (field) => {
      if (field.editVariantProps?.fetchFromAPI) {
        const paramKeys = field.editVariantProps.parentParamsKey || [];
        const params = modifiedFormDataFields
          .filter((field) => paramKeys.indexOf(field.masterKey || '') > -1)
          .map((element) => element.value);
        const dropdownData = await transformAPIdropDownData(
          apiVersion,
          field?.editVariantProps,
          getArgs(field, formApiKey, searchAccountUserDetails, params as string[]),
          formApiKey as string,
        );

        field.editVariantProps.dropdownData = dropdownData;

        field.editVariantProps.selectedDropdownOption = dropdownData?.filter(
          (dropDown: Data) => dropDown.id === (field?.value as string) || dropDown.title === (field?.value as string),
        )?.[0];
      }
      const parentField = modifiedFormDataFields?.find((element) => element.masterKey === field.parentDependentKey);

      if (
        field.dependencyVisibilityList &&
        parentField &&
        field.dependencyVisibilityList.includes(parentField?.editVariantProps?.selectedDropdownOption?.id as string)
      ) {
        field.isDependentVisible = true;
      }
      return field;
    }),
  );

export const getArgs = (
  field: DynamicField,
  formApiKey: string | undefined,
  searchAccountUserDetails: GenericAny,
  params: string[],
) => {
  switch (field?.editVariantProps?.dataKey) {
    case ApiDropDownKey.BANK_NAME:
      return formApiKey === FormAPIKey.BANK_ACCOUNT_ADD_BONUS_REMITTANCE ||
        formApiKey === FormAPIKey.BANK_ACCOUNT_EDIT_BONUS_REMITTANCE
        ? [searchAccountUserDetails.accountDetails.accountMst.cntryCd]
        : ['VE'];
    case ApiDropDownKey.BANK_BRANCH_NAME: {
      const bankId =
        searchAccountUserDetails.accountDetails.mappedBankAccountDetail[
          FormAPIKey.BANK_ACCOUNT_EDIT_BONUS_REMITTANCE ? 'bonusRemittance' : 'secondaryRemittance'
        ]?.issuingBankId;
      return [
        bankId,
        formApiKey === FormAPIKey.BANK_ACCOUNT_EDIT_BONUS_REMITTANCE
          ? searchAccountUserDetails.accountDetails.accountMst.cntryCd
          : 'VE',
      ];
    }
    default:
      return params;
  }
};

export const infoMessageSetup = (
  selectedOption: string | DropDownDataInterface | boolean,
  masterKey: string | undefined,
  formFields: GenericAny,
  setShowInfo: Function,
  setInfoMessage: Function,
  setPostalCodeRange: Function,
) => {
  const field = formFields.find((f: GenericAny) => f.masterKey === masterKey);
  const country = formFields.find((f: GenericAny) => f.masterKey === 'cntryCd')?.value; // Get country name from the field

  const dropdownSelect = selectedOption as Data;

  switch (masterKey) {
    case 'cityName':
      if (portalCodeFromCity.includes(country)) {
        const [from, to] = field.editVariantProps.hiddendata[dropdownSelect.id as string].split('-');
        setPostalCodeRange({ from: +from, to: +to });
      }
      setInfoMessage(`Valid postal code range from ${field.editVariantProps.hiddendata[dropdownSelect.id as string]}`);
      setShowInfo(true);
      break;
    case 'muncipal':
      if (portalCodeFromColony.includes(country)) {
        const [from, to] = field.editVariantProps.hiddendata[dropdownSelect.id as string].split('-');
        setPostalCodeRange({ from: +from, to: +to });
      }

      setInfoMessage(`Valid postal code range from ${field.editVariantProps.hiddendata[dropdownSelect.id as string]}`);
      setShowInfo(true);
      break;
    case 'parish':
      if (postalCodeFromParish.includes(country)) {
        const [from, to] = field.editVariantProps.hiddendata[dropdownSelect.id as string].split('-');
        setPostalCodeRange({ from: +from, to: +to });
      }

      setInfoMessage(`Valid postal code range from ${field.editVariantProps.hiddendata[dropdownSelect.id as string]}`);
      setShowInfo(true);
      break;
    default:
      setShowInfo(false);
      setInfoMessage('');
  }
};

interface PostalDataResult {
  [key: string]: string;
}

export const generatePostalData = (
  portalCodeList: string[],
  country: string,
  localities: GenericAny[],
  localityCdKey: string,
  fromPostalCdKey: string,
  toPostalCdKey: string,
) => {
  const result: PostalDataResult = {};

  if (portalCodeList.includes(country)) {
    localities.forEach((item) => {
      const localityCd = item[localityCdKey];
      const fromPostalCd = item[fromPostalCdKey];
      const toPostalCd = item[toPostalCdKey];

      result[localityCd] = `${fromPostalCd} - ${toPostalCd}`;
    });
  }

  return result;
};

export const fetchPostalCode = async (
  masterKey: string | undefined,
  prevValue: DynamicField[],
  fieldIndex: number,
  selectedOption: string | DropDownDataInterface | boolean,
) => {
  const paramKeys = prevValue[fieldIndex]?.editVariantProps?.parentParamsKey || [];
  const params = prevValue
    .filter((field) => paramKeys.indexOf(field.masterKey || '') > -1)
    .map((element) => element.editVariantProps?.selectedDropdownOption?.id);
  const dropdownValue = selectedOption as Data;
  switch (masterKey) {
    case 'muncipal':
      {
        const municipal = dropdownValue.title as string;
        const [country, stateId, cityId] = params;

        try {
          const { localities } = await mdmsAccountApi.getLocalities(country as string, {
            locality1Cd: stateId as string,
            locality2Cd: cityId as string,
            locality3Cd: municipal,
          });
          const modifiedLocalityList = localities.map((locality: GenericAny) => ({
            ...locality,
            localityName: municipal,
          }));
          const postalCodes = generatePostalData(
            portalCodeFromColony,
            country as string,
            modifiedLocalityList,
            'localityName',
            'localityCd',
            'localityNm',
          );
          if (prevValue?.[fieldIndex]?.editVariantProps) {
            (prevValue[fieldIndex] as any).editVariantProps.hiddendata = postalCodes;
          }
        } catch (error) {
          loggerInstance.error(error);
        }
      }
      break;
    case 'parish':
      {
        const parish = dropdownValue.title as string;
        const [country, stateId, cityId, municipal] = params;
        try {
          const { localities } = await mdmsAccountApi.getLocalities(country as string, {
            locality1Cd: stateId as string,
            locality2Cd: cityId as string,
            locality3Cd: municipal as string,
            locality4Cd: parish,
          });
          const modifiedLocalityList = localities.map((locality: GenericAny) => ({
            ...locality,
            localityName: parish,
          }));
          const postalCodes = generatePostalData(
            postalCodeFromParish,
            country as string,
            modifiedLocalityList,
            'localityName',
            'localityCd',
            'localityNm',
          );
          if (prevValue?.[fieldIndex]?.editVariantProps) {
            (prevValue[fieldIndex] as any).editVariantProps.hiddendata = postalCodes;
          }
        } catch (error) {
          loggerInstance.error(error);
        }
      }

      break;

    //no default
  }
};