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

import static com.app.simplitend.welcome.welcomepatient.fragments.contacts.CreateContactFragment.CONTACT_KEY;
import static com.app.simplitend.welcome.welcomepatient.fragments.contacts.CreateContactFragment.TO_EDIT_KEY;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
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.databinding.ContactInfoFragmentBinding;
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.mvvm.WelcomeContracts;
import com.bumptech.glide.Glide;
import com.skydoves.powerspinner.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.Arrays;

public class ContactInfoFragment extends Fragment implements WelcomeContracts.DeleteContactInterface {

    // view binding
    protected ContactInfoFragmentBinding binding;

    /*
        This flag defines weather user want to connect with selected phone number
        by CALLING OR MESSAGING THEM
        0 : CALLING
        1 : MESSAGING
     */
    private int CONTACT_BY = 0;

    public static final String CONTACT_DATA_KEY = "contact_key";

    private ContactData contactData;

    private ContactViewModel contactViewModel;

    private ProgressDialog progressDialog;

    private ArrayList<String> contactLIst;

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

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

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

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {

        if (getArguments() != null && getArguments().getSerializable(CONTACT_DATA_KEY) != null) {
            contactData = (ContactData) getArguments().getSerializable(CONTACT_DATA_KEY);
        } else {
            // no arguments received
            Activity activity = getActivity();
            if (activity != null){
                activity.onBackPressed();
            }
            return;
        }

        progressDialog = new ProgressDialog(requireContext());
        contactLIst = new ArrayList<>();

        binding.phoneSpinner.setIsFocusable(true);
        binding.phoneSpinner.setDismissWhenNotifiedItemSelected(true);
        binding.phoneSpinner.setLifecycleOwner(this);

        binding.phoneSpinner.setOnSpinnerItemSelectedListener((OnSpinnerItemSelectedListener<String>) (i, s, i1, t1) -> {
            if (t1 == null) return;

            if (CONTACT_BY == 0){
                callNumber(t1);
            }else{
                messageNumber(t1);
            }
        });

        loadUserData();

    }

    private void loadUserData() {
        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);
        }

        binding.name.setText(contactData.first_name);
        binding.phoneNumber.setText(contactData.phone_number);

        if (contactData.email_address != null)
        {
            binding.email.setText(contactData.email_address);
        }else{
            binding.email.setText("None");
        }

        if (contactData.relationship == null || contactData.relationship.trim().isEmpty()){
            binding.relationship.setVisibility(View.GONE);
            binding.relationshipTag.setVisibility(View.GONE);
        }

        if (contactData.is_sos.equals("1")){
            binding.relationship.setText(contactData.relationship + "( Emergency contact )");
        }else{
            binding.relationship.setText(contactData.relationship);
        }

        contactLIst.add(contactData.phone_number);

        if (contactData.extra_phone_numbers != null){
            String[] extra_numbers = contactData.extra_phone_numbers.split(",");
            contactLIst.addAll(Arrays.asList(extra_numbers));
        }

        // configuring contact spinner
        binding.phoneSpinner.setItems(contactLIst);

    }

    private void clickEvents() {

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

        binding.delete.setOnClickListener(v -> {

            if (contactData.care_giver_data.id != null){
                // This is a caregiver contact
                // thus, cannot be deleted
                Toast.makeText(requireContext(), "You cannot delete caregiver contact.", Toast.LENGTH_SHORT).show();
                return;
            }

            if (contactData.is_doctor != null && contactData.is_doctor.equals("1")){
               // cannot delete doctor
                Toast.makeText(requireContext(), "You cannot delete your primary doctor.", Toast.LENGTH_SHORT).show();
                return;
            }

            AppUtil.showSOSDecision(requireContext(),
                    getString(R.string.sure_delete),
                    getString(R.string.yes),
                    getString(R.string.no),
                    yes -> {
                        progressDialog.setTitle("Please wait");
                        progressDialog.setMessage("while we delete the contact details.");
                        progressDialog.setCancelable(false);
                        progressDialog.show();

                        contactViewModel.deleteContact(AppUtil.getPatientToken(requireContext()),
                                contactData.contact_id, this);
                    }, no -> {
                        // nothing to do
                    });
        });

        binding.edit.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putBoolean(TO_EDIT_KEY, true);
            bundle.putSerializable(CONTACT_KEY, contactData);

            try {
                Navigation.findNavController(v)
                        .navigate(R.id.action_contactInfoFragment_to_createContactFragment, bundle);
            }catch (Exception e){
                try {
                    getParentFragmentManager().beginTransaction()
                            .replace(R.id.fcv_profile_shower, CreateContactFragment.class, bundle)
                            .addToBackStack("create_contact_f")
                            .commitAllowingStateLoss();
                } catch (Exception ex) {
                    // user may be out of context
                }
            }
        });

        binding.callBtn.setOnClickListener(v -> {
            CONTACT_BY = 0;

            if (contactLIst != null){
                if (contactLIst.size() == 1){
                    callNumber(contactData.phone_number);
                }else{
                    binding.phoneSpinner.show();
                }
            }
        });

        binding.messageBtn.setOnClickListener(v -> {
            CONTACT_BY = 1;

            if (contactLIst != null){
                if (contactLIst.size() == 1){
                    messageNumber(contactData.phone_number);
                }else{
                    binding.phoneSpinner.show();
                }
            }
        });

    }

    private void callNumber(String phone_number){
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                phone_number,
                null));
        startActivity(intent);
    }

    private void messageNumber(String phone_number){
        Uri uri = Uri.parse("smsto:" + phone_number);
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
//            intent.putExtra("sms_body", "The SMS text");
        startActivity(intent);
    }

    @Override
    public void onContactDelete() {
        progressDialog.dismiss();
        Toast.makeText(requireActivity(), "Contact deleted successfully.", Toast.LENGTH_SHORT).show();
        Activity activity = getActivity();
        if (activity != null){
            activity.onBackPressed();
        }
    }

    @Override
    public void onContactDeleteFailed() {
        progressDialog.dismiss();
        Toast.makeText(requireActivity(), "Contact deleted successfully.", Toast.LENGTH_SHORT).show();
    }
}
