package com.app.simplitend.welcome.welcomepatient.fragments.contacts;

import static com.app.simplitend.apputils.RetrofitHelper.CREATE_CONTACT;
import static com.app.simplitend.apputils.RetrofitHelper.UPDATE_CONTACT;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.apputils.TextUtils;
import com.app.simplitend.databinding.CreateContactViewHolderBinding;
import com.app.simplitend.databinding.CreateEditContactFragmentBinding;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.Contact;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.ContactViewModel;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.models.ContactData;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.models.ContactListResponse;
import com.app.simplitend.welcome.welcomepatient.mvvm.WelcomeContracts;
import com.bumptech.glide.Glide;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.skydoves.powerspinner.PowerSpinnerView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class CreateContactFragment extends Fragment implements WelcomeContracts.ContactListContracts,
        ContactViewModel.GotoAddContactInterface, ContactViewModel.SOSCheckInterface,
        WelcomeContracts.CreateContactInterface, WelcomeContracts.UpdateContactContracts {

    // log tag
    private static final String TAG = "CreateContactFragment";

    // view binding
    protected CreateEditContactFragmentBinding binding;

    private ProgressDialog progressDialog;

    // arguments keys
    public static final String TO_EDIT_KEY = "to_edit";
    public static final String CONTACT_KEY = "contact_key";

    // flag if current instance is to edit or create contact
    boolean to_edit;

    // image selector launcher
    private ActivityResultLauncher<Intent> imageSelector;

    private ContactViewModel contactViewModel;

    private ArrayList<String> countryCodeList;

    // flag indicating that current contact must be a caregiver or not
    private boolean mustBeeCaregiver;

    // image selected uri
    private Uri selectedImageUri;
    private ContactData contactData;

    // Remote contact list
    protected List<ContactListResponse> contactList;

    private boolean isSosSet, current_contact_sos;
    private String sos_contact_name;

    public CreateContactFragment() {
        // required empty const.
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = CreateEditContactFragmentBinding.inflate(inflater, container, false);

        contactViewModel = new ViewModelProvider(requireActivity()).get(ContactViewModel.class);

        // interfaces
        contactViewModel.setSosCheckInterface(this);
        contactViewModel.setGotoAddContactInterface(this);

        initializeViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initializeViews() {

        // country code loading
        countryCodeList = contactViewModel.loadCountryCodeDropDown(requireContext());
        if (countryCodeList == null) countryCodeList = new ArrayList<>();
        if (!countryCodeList.contains("+1")) {
            countryCodeList.add("+1");
        }

        progressDialog = new ProgressDialog(requireContext());

        Bundle bundle = getArguments();

        if (bundle != null) {
            to_edit = bundle.getBoolean(TO_EDIT_KEY, false);

            if (to_edit) {
                setLayoutDetails(getString(R.string.edit_contact), getString(R.string.change_photo), getString(R.string.save));
            } else {
                setLayoutDetails(getString(R.string.create_contact), getString(R.string.add_photo), getString(R.string.save));
            }

            if (bundle.getSerializable(CONTACT_KEY) != null) {
                contactData = (ContactData) bundle.getSerializable(CONTACT_KEY);
                setDetails();
            } else {
                addContactView("", true);
            }
        }

        loadRemoteContactList();

        binding.sosCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked && !current_contact_sos) {
                contactViewModel.showSOSDecision(requireContext(), isSosSet, sos_contact_name,
                        binding.name.getText().toString());
            }else if (!isChecked && current_contact_sos){
                // changing sos to 911
                AppUtil.showSOSDecision(requireContext(),
                        getString(R.string.you_are_about_to_change_emergency_number_from_this_contact_to_911_please_confirm),
                        getString(R.string.yes), getString(R.string.no),
                        v -> {
                        }, v -> {
                            binding.sosCheck.setChecked(true);
                        });
            }
        });

        binding.caregiverCheck.setOnCheckedChangeListener(((buttonView, isChecked) -> {
            if (!isChecked && mustBeeCaregiver) {
                binding.caregiverCheck.setChecked(true);
                Toast.makeText(requireContext(), "This contact should be a caregiver.", Toast.LENGTH_SHORT).show();
            }
        }));

        binding.email.addTextChangedListener(TextUtils.LEADING_SPACE_WATCHER);

        imageSelector = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        //Image Uri will not be null for RESULT_OK
                        selectedImageUri = result.getData().getData();

                        binding.image.setImageURI(null);
                        binding.image.setImageURI(selectedImageUri);

                        Log.d(TAG, "initializeViews: " + selectedImageUri.getPath());
                    } else if (result.getResultCode() == ImagePicker.RESULT_ERROR) {
                        Toast.makeText(requireContext(), ImagePicker.getError(result.getData()), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(requireContext(), "Task Cancelled", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void clickEvents() {

        binding.backBtn.setOnClickListener(v -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });

        binding.cancelBtn.setOnClickListener(view -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });

        binding.nextBtn.setOnClickListener(v -> {

            String[] phone_numbers = getAllPhoneNumbers();

            if (!phone_numbers[3].equals("0")) {
                AppUtil.showAlert(requireContext(),
                        "Select a default number",
                        "Your contact has multiple phone numbers. Please set one as the default. All numbers will be saved in the contact, and you will still be able to access them.",
                        getString(R.string.ok),
                        (dialogInterface, i) -> {}, null, null);
                return;
            }

            if (allOkay() && phone_numbers[2].equals("0")) {
                if (to_edit) {
                    // editing existing contact

                    AppUtil.showSOSDecision(requireContext(),
                            getString(R.string.make_changes),
                            getString(R.string.yes),
                            getString(R.string.no),
                            yes -> {
                                createEditContact("While we update your contact details.", true,
                                        UPDATE_CONTACT + contactData.contact_id, phone_numbers);
                            }, no -> {

                            });

                } else {
                    createEditContact("While we save the contact details.", false,
                            CREATE_CONTACT, phone_numbers);
                }
            }

        });

        binding.image.setOnClickListener(v -> {

            ImagePicker.with(requireActivity())
                    .cropSquare()
                    .maxResultSize(500, 500)
                    .galleryOnly()
                    .createIntent(intent -> {
                        imageSelector.launch(intent);
                        return null;
                    });

        });

    }

    private void createEditContact(String progressMsg, boolean edit_contact,
                                   String URL, String[] phoneNumbers) {

        progressDialog.setTitle("Please wait");
        progressDialog.setMessage(progressMsg);
        progressDialog.setCancelable(false);
        progressDialog.show();

        Map<String, RequestBody> body = new HashMap<>();
        RequestBody user_first_name = RequestBody.create(binding.name.getText().toString().trim(), MediaType.parse("text/plain;charset=utf-8"));
        body.put("full_name", user_first_name);

        RequestBody contact_number_part = RequestBody.create(phoneNumbers[0], MediaType.parse("text/plain;charset=utf-8"));
        body.put("contact_number", contact_number_part);

        RequestBody extra_contact_number_part = RequestBody.create(phoneNumbers[1], MediaType.parse("text/plain;charset=utf-8"));
        body.put("extra_phone_numbers", extra_contact_number_part);

        RequestBody email_ = RequestBody.create(binding.email.getText().toString().trim(), MediaType.parse("text/plain;charset=utf-8"));
        body.put("email_address", email_);

        RequestBody relationship_ = RequestBody.create(binding.relationship.getText().toString().trim(), MediaType.parse("text/plain;charset=utf-8"));
        body.put("relationship", relationship_);

        Map<String, Integer> intBody = new HashMap<>();

        intBody.put("is_sos", binding.sosCheck.isChecked() ? 1 : 0);
        intBody.put("is_caregiver_contact", binding.caregiverCheck.isChecked() ? 1 : 0);
        intBody.put("patient_xid", AppUtil.getPatientUid(requireContext()));

        MultipartBody.Part filePart = null;

        if (selectedImageUri != null) {
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), new File(selectedImageUri.getPath()));
            filePart = MultipartBody.Part.createFormData("contact_photo",
                    "img_" + System.currentTimeMillis()
                    , requestFile);
        }

        contactViewModel.createEditContact(
                URL,
                body,
                intBody,
                filePart,
                edit_contact ? null : this, // create contact call back
                edit_contact ? this : null, // update contact call back
                "Bearer " + AppUtil.getPatientToken(requireContext()));

    }

    private boolean allOkay() {
        boolean allOkay = true;

        if (binding.name.getText().toString().trim().isEmpty()) {
            allOkay = false;
            binding.name.setError("Required");
        }

        if (mustBeeCaregiver && binding.email.getText().toString().trim().isEmpty()) {
            allOkay = false;
            binding.email.setError("Required");
        }else if (mustBeeCaregiver && !Patterns.EMAIL_ADDRESS.matcher(binding.email.getText().toString()).matches()){
            allOkay = false;
            binding.email.setError("Invalid email");
        }else if (!mustBeeCaregiver && !binding.email.getText().toString().isEmpty() && !Patterns.EMAIL_ADDRESS.matcher(binding.email.getText().toString()).matches()){
            // optional email is not blank and invalid
            allOkay = false;
            binding.email.setError("Invalid email");
        }

//        if (binding.countryCodes.getSelectedIndex() == -1 && allOkay) {
//            allOkay = false;
//            Toast.makeText(requireContext(), "please select a country code", Toast.LENGTH_SHORT).show();
//        }

        return allOkay;
    }

    @Override
    public void gotoAddFragment(BottomSheetDialog bsd) {
        new Handler().postDelayed(() -> {
            if (bsd != null) bsd.dismiss();

            Toast.makeText(requireActivity(), "Contact updated successfully.", Toast.LENGTH_SHORT).show();
            try {
                Navigation.findNavController(binding.getRoot()).popBackStack(R.id.addContactFragment, false);
            } catch (Exception e) {
                // this fragment is not only opened by the welcome_nav_graph
                try {
                    getParentFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                } catch (Exception e2) {
                    // user may be out of context
                }
            }

        }, 3600);
    }

    @Override
    public void onCheckChange(boolean state) {
        binding.sosCheck.setChecked(state);
    }

    // remote call back fetching callBack
    @Override
    public void onResponse(List<ContactListResponse> contactList) {
        Log.d(TAG, "onResponse: " + contactList);

        this.contactList = contactList;

        if (contactList.size() == 0) {
            // there are no contacts in remote database
            // thus, this contact has to be a caregiver
            binding.relationship.setText(getString(R.string.caregiver));
            binding.relationship.setEnabled(false);

            //email is important
            binding.emailTitle.setText(getString(R.string.email_address)); // with asterisk
            binding.emailOptional.setVisibility(View.GONE);
            binding.relationOptional.setVisibility(View.GONE);

            binding.caregiverCheckView.setVisibility(View.VISIBLE);
            this.mustBeeCaregiver = true;
            binding.caregiverCheck.setChecked(true);

            // setting up title
            setLayoutDetails(getString(R.string.create_caregiver_contact), getString(R.string.add_photo), getString(R.string.save));
            addContactView("", true);
        }

        // checking if there is any SOS contact already in list
        isSosSet = false;
        int sos_contact_id = -1;

        for (ContactListResponse contact : contactList) {
            if (contact.contact_data != null) {
                if (contact.contact_data.is_sos.equals("1")) {
                    isSosSet = true;

                    sos_contact_id = contact.contact_data.id;
                    sos_contact_name = contact.contact_data.first_name;
                    break;
                }
            }
        }

        current_contact_sos = false;

        if (isSosSet) {
            binding.defaultSos.setVisibility(View.GONE);

            if (contactData != null && sos_contact_id != -1 && sos_contact_id == contactData.id) {
                // current contact being edited is the SOS contact
                // thus, sos switch can be edited
                current_contact_sos = true;
                binding.sosCheckView.setVisibility(View.VISIBLE);
            }

        } else {
            binding.defaultSos.setVisibility(View.VISIBLE);
        }

        progressDialog.dismiss();
    }

    @Override
    public void onFailure(Throwable t, String message, int error_code) {
        Log.e(TAG, "onFailure: message : " + message + "\n", t);

        progressDialog.dismiss();

        Activity activity = getActivity();
        if (activity != null) {
            activity.onBackPressed();
        }

        Toast.makeText(requireContext(), "Couldn't load contact", Toast.LENGTH_SHORT).show();
    }

    // create contact callback
    @Override
    public void onContactCreated(Contact contact) {
        Log.d(TAG, "onContactCreated: " + contact);
        progressDialog.dismiss();

        try {
            Navigation.findNavController(binding.getRoot()).navigate(R.id.action_createContactFragment_to_addContactFragment);
        } catch (Exception e) {
            // this fragment is opened from outside of welcome_nav_graph
            try {
                getParentFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            } catch (Exception ex) {
                // user may be out of context
            }
        }
    }

    @Override
    public void onContactCreateFailed(Throwable t, String message, int error_code) {
        Log.d(TAG, "onContactCreateFailed: " + t.getMessage());
        progressDialog.dismiss();

        AppUtil.showAlert(requireContext(), "Something went wrong",
                message, getString(R.string.OK),
                (dialog, which) -> {
                    dialog.dismiss();
                }, null, null);

    }

    @Override
    public void onContactUpdated() {
        progressDialog.dismiss();
        contactViewModel.showDoneBottomSheet(requireContext());
    }

    @Override
    public void onUpdateFailed() {
        progressDialog.dismiss();
        Toast.makeText(requireActivity(), "Contact update failed.", Toast.LENGTH_SHORT).show();
    }

    // loading remote contact list to know whether this is user's first contact
    private void loadRemoteContactList() {

        progressDialog.setTitle("Please wait");
        progressDialog.setMessage("Loading contact details");
        progressDialog.setCancelable(false);
        progressDialog.show();

        String token = "Bearer " + AppUtil.getPatientToken(requireContext());
        contactViewModel.getRemoteContactList(this, token);
    }

    private void setDetails() {
        if (contactData == null) {
            return;
        }

        if (contactData.contact_photo != null) {
            Glide.with(requireContext())
                    .load(RetrofitHelper.IMAGE_BASE_URL + contactData.contact_photo)
                    .placeholder(android.R.color.darker_gray)
                    .error(R.drawable.ic_contact)
                    .fitCenter().into(binding.image);
        }else if (contactData.photo_uri != null){
            Glide.with(requireContext())
                    .load(contactData.photo_uri)
                    .placeholder(android.R.color.darker_gray)
                    .error(R.drawable.ic_contact)
                    .fitCenter().into(binding.image);
            
            selectedImageUri = contactViewModel.accessPHotoUri(requireContext(), contactData.photo_uri);
            Log.d(TAG, "setDetails: ");
        }

        if (contactData.first_name != null) {
            binding.name.setText(contactData.first_name);
        }

        if (contactData.email_address != null)
            binding.email.setText(contactData.email_address);

        if (contactData.relationship != null)
            binding.relationship.setText(contactData.relationship);

        if (contactData.is_sos != null && contactData.is_sos.equals("1")) {
            binding.sosCheck.setChecked(true);
        }

        // if caregiver, cannot change email and phone number
        if (contactData.care_giver_data != null && contactData.care_giver_data.id != null) {
            binding.email.setClickable(false);
            binding.email.setFocusable(false);
            binding.emailTitle.setText(getString(R.string.email_address));

            binding.caregiverCheckView.setVisibility(View.VISIBLE);
            binding.caregiverCheck.setChecked(true);
            binding.caregiverCheck.setEnabled(false);
            binding.relationship.setEnabled(false);

            binding.relationOptional.setVisibility(View.GONE);
            binding.emailOptional.setVisibility(View.GONE);
        }

        // checking if this contact is doctor
        if (contactData.is_doctor != null && contactData.is_doctor.equals("1")){
            // this contact is doctor
            binding.name.setEnabled(false);
            binding.relationship.setEnabled(false);

            binding.relationOptional.setVisibility(View.GONE);
        }else{
            binding.name.setEnabled(true);
            binding.relationship.setEnabled(true);
        }

        boolean default_contact_set = false;
        if (contactData.phone_number != null) {
            addContactView(contactData.phone_number, default_contact_set = true);
        }

        // adding contacts to Contact_rv
        if (contactData.extra_phone_numbers != null && !contactData.extra_phone_numbers.isEmpty()) {
            String[] phone_numbers = contactData.extra_phone_numbers.split(",");

            for (String phone_number : phone_numbers) {
                addContactView(phone_number, phone_numbers.length == 1 && !default_contact_set);
            }
        }

    }

    private void addContactView(String contact_number, boolean id_default) {
        CreateContactViewHolderBinding contact_binding = CreateContactViewHolderBinding.inflate(getLayoutInflater());

        contact_binding.createCountryCodes.setItems(countryCodeList);
        contact_binding.createCountryCodes.setIsFocusable(true);
        contact_binding.createCountryCodes.setDismissWhenNotifiedItemSelected(true);

        contact_binding.createCountryCodes.setOnClickListener(v -> {
            AppUtil.closeKeyboard(requireActivity());
            contact_binding.createCountryCodes.showOrDismiss();
        });

        // phone number formatting
        // to deal with input pasting in the edit text
        InputFilter phoneFilter = (charSequence, i, i1, spanned, i2, i3) -> {
            String phone_number_str = charSequence.toString();

            String country_code;

            if (contact_binding.createCountryCodes.getSelectedIndex() == -1) {
                country_code = "+1";
            } else {
                country_code = countryCodeList.get(contact_binding.createCountryCodes.getSelectedIndex());
            }

            try {
                PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
                Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(charSequence, "US");

                phone_number_str = String.valueOf(phoneNumber.getNationalNumber());
                country_code = "+" + phoneNumber.getCountryCode();
            } catch (Exception e) {
                // nothing
            }

            if (!countryCodeList.contains(country_code)) {
                countryCodeList.add(country_code);
            }

            contact_binding.createCountryCodes.selectItemByIndex(countryCodeList.indexOf(country_code));

            if (phone_number_str.length() > 10) {
                // pasted number length is greater than 10
                return phone_number_str.substring(0, 10);
            }

            String total_phone_number = contact_binding.createPhoneNumber.getText().toString() + phone_number_str;

            if (total_phone_number.length() > 10) {
                // max length should be 10
                return "";
            } else {
                return phone_number_str;
            }
        };

        contact_binding.createPhoneNumber.setFilters(new InputFilter[]{phoneFilter});

        contact_binding.createPhoneNumber.setText(contact_number);

        contact_binding.defaultCheck.setOnClickListener(v -> {
            if (!contact_binding.defaultCheck.isSelected()) {
                selectDefaultContact(binding.contactTable.indexOfChild(contact_binding.getRoot()));
            }
        });

        contact_binding.delete.setOnClickListener(v -> {
            if (binding.contactTable.getChildCount() == 1) {
                Toast.makeText(requireContext(), "Cannot be deleted", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                binding.contactTable.removeView(contact_binding.getRoot());
            } catch (Exception e) {
                Toast.makeText(requireContext(), "Couldn't delete contact.", Toast.LENGTH_SHORT).show();
            }
        });

        contact_binding.defaultCheck.setSelected(id_default);

        // if contact is a doctor we wont allow the contact to be changes
        if (contactData != null && contactData.is_doctor != null && contactData.is_doctor.equals("1")){
            contact_binding.createPhoneNumber.setEnabled(false);
            contact_binding.createCountryCodes.setEnabled(false);
            contact_binding.defaultCheck.setEnabled(false);
        }

        binding.contactTable.addView(contact_binding.getRoot());
    }

    private void selectDefaultContact(int index) {
        int count = binding.contactTable.getChildCount();
        if (index >= 0 && index < count) {
            // unselecting all other editBoxes
            for (int i = 0; i < count; i++) {
                View view = binding.contactTable.getChildAt(i);
                if (view != null) {
                    ImageButton default_check = view.findViewById(R.id.default_check);
                    if (default_check != null) {

                        if (i == index) {
                            default_check.setSelected(true);
                        } else {
                            default_check.setSelected(false);
                        }

                    }
                }
            }
        }
    }

    /*
        returns a string array of size 2
        index 0: default phone number
        index 1: extra phone number separated by ','
        index 2: error code
        index 3: if default number is selected or not 0 = default number selected and vice versa
     */
    public String[] getAllPhoneNumbers() {
        String[] phone_numbers = {"", "", "0", "1"};
        int count = binding.contactTable.getChildCount();

        for (int i = 0; i < count; i++) {
            View view = binding.contactTable.getChildAt(i);
            if (view != null) {
                ImageButton default_check = view.findViewById(R.id.default_check);
                EditText phone_input = view.findViewById(R.id.create_phone_number);

                // getting country code
                PowerSpinnerView countryCodeView = view.findViewById(R.id.create_country_codes);
                String countryCode = "+1";

                if (countryCodeView != null) {
                    int selected_cc_index = countryCodeView.getSelectedIndex();
                    if (selected_cc_index > -1 && selected_cc_index < countryCodeList.size()) {
                        countryCode = countryCodeList.get(selected_cc_index);
                    }
                }

                if (default_check != null && phone_input != null) {

                    phone_input.setError(null);

                    if (phone_input.getText().toString().trim().isEmpty()) {
                        phone_input.setError("Cannot be empty");
                        phone_numbers[2] = "1";
                    }

                    if (default_check.isSelected()) {
                        phone_numbers[0] = (countryCode + phone_input.getText().toString());
                        phone_numbers[3] = "0";

                        // validating phone number
                        try {
                            Phonenumber.PhoneNumber phone_number = PhoneNumberUtil.getInstance().parse(phone_numbers[0], "US");
                            if (!PhoneNumberUtil.getInstance().isValidNumber(phone_number)) {
                                phone_input.setError("Invalid number");
                                phone_numbers[2] = "1";
                            }
                        } catch (Exception e) {
                            // do nothing as we couldn't validate phone number
                        }

                    } else {
                        phone_numbers[1] += (countryCode + phone_input.getText().toString() + ",");
                    }

                }
            }
        }

        // removing last "," added
        int last_index = Math.max(phone_numbers[1].length() - 1, 0);
        phone_numbers[1] = phone_numbers[1].substring(0, last_index);

        return phone_numbers;
    }

    public void setLayoutDetails(String title, String photo_title, String btn_txt) {
        binding.title.setText(title);
        binding.photoTv.setText(photo_title);
        binding.nextBtn.setText(btn_txt);
    }

}