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

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

import android.app.Activity;
import android.app.ProgressDialog;
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 androidx.recyclerview.widget.GridLayoutManager;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.databinding.AddContactFragmentBinding;
import com.app.simplitend.databinding.DoneBottomsheetBinding;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.AddContactAdapter;
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.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;
import java.util.List;

public class AddContactFragment extends Fragment implements WelcomeContracts.ContactListContracts, AddContactAdapter.ContactClickListener {

    // view binding
    protected AddContactFragmentBinding binding;

    public static final String CONTACT_INFO_F = "contact_info_f";

    protected AddContactAdapter contactAdapter;

    private ProgressDialog progressDialog;

    private ContactViewModel contactViewModel;

    private int contacts_count;
    private boolean is_doctor_set;

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

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

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

        initViews();

        clickEvents();
        
        return binding.getRoot();
    }

    private void initViews() {

        progressDialog = new ProgressDialog(requireContext());

        binding.contactRv.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        contactAdapter = new AddContactAdapter();
        binding.contactRv.setAdapter(contactAdapter);

        loadContacts();

    }

    private void loadContacts() {

        binding.progressBar.setVisibility(View.VISIBLE);
        contactViewModel.getRemoteContactList(this,
                "Bearer " + AppUtil.getPatientToken(requireContext()));

        contactAdapter.setContactClickListener(this);
        
    }

    private void clickEvents() {

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

        binding.nextBtn.setOnClickListener(v ->
        {
            try {
                Navigation.findNavController(v).navigate(R.id.action_addContactFragment_to_profileProgressFragment);
            }catch (Exception e){
                // this fragment is not only opened by the welcome_nav_graph
                // but, also by other fragments
                Activity activity = getActivity();
                if (activity != null){
                    activity.onBackPressed();
                }
            }
        });

    }

    @Override
    public void onResponse(List<ContactListResponse> responseList) {
        this.contacts_count = responseList.size();

        ArrayList<ContactData> contactList = new ArrayList<>();
        
        for (ContactListResponse response : responseList){
            response.contact_data.contact_id = response.id;
            response.contact_data.is_doctor = response.is_doctor;
            if (response.is_doctor != null){
                this.is_doctor_set = response.is_doctor.equals("1");
            }
            contactList.add(response.contact_data);
        }

        PatientDataCache.setContactList(new ArrayList<>(contactList));
        try {
            AppUtil.setWhiteListedContacts(requireContext(), contactList);
        } catch (Exception e) {
            // do nothing
        }

        for (int i = contactList.size(); i<10; i++){
            contactList.add(new ContactData(-1));
        }

        binding.progressBar.setVisibility(View.GONE);

        contactAdapter.submitList(contactList);

        binding.nextBtn.setVisibility(View.VISIBLE);
    }

    @Override
    public void onFailure(Throwable t, String message, int error_code) {
        try {
            Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // do nothing
        }
        binding.progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onContactClick(ContactData contactData, int position) {

        if (contactData.id == -1){
            // a new contact should be added

            if (contacts_count == 9 && !is_doctor_set){
                // last contact to be added
                // and doctor not yet set
                AppUtil.showAlert(requireContext(),
                        "This contact is reserved",
                        "Last contact is reserved for your primary doctor. Once you complete your medical information, the contact information will be filled in automatically.",
                        getString(R.string.ok), ((dialogInterface, i) -> {}), null, null);
                return;
            }

            AppUtil.showAlert(requireContext(),
                    "Select contact",
                    "Add from contacts or manually?",
                    "Contacts",
                    ((dialogInterface, i) -> {
                        try {
                            Navigation.findNavController(binding.getRoot())
                                    .navigate(R.id.action_addContactFragment_to_contactListFragment);
                        }catch (Exception e){
                            // this fragment is also opened by other context
                            try {
                                getParentFragmentManager().beginTransaction()
                                        .replace(R.id.fcv_profile_shower, ContactListFragment.class, null)
                                        .addToBackStack("contact_list_f")
                                        .commitAllowingStateLoss();
                            } catch (Exception ex) {
                                // user may be out of context
                            }
                        }
                    }),
                    "Manually",
                    ((dialogInterface, i) -> {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(TO_EDIT_KEY, false);

                        try {
                            Navigation.findNavController(binding.getRoot())
                                    .navigate(R.id.action_addContactFragment_to_createContactFragment, bundle);
                        }catch (Exception e){
                            // this fragment is also opened by other context
                            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
                            }
                        }
                    })
                    );

        }else{
            // show contact details
            Bundle bundle = new Bundle();
            bundle.putSerializable(CONTACT_DATA_KEY, contactData);

            try {
                Navigation.findNavController(binding.getRoot())
                        .navigate(R.id.action_addContactFragment_to_contactInfoFragment, bundle);
            }catch (Exception e){
                // this fragment is also opened by other context
                try {
                    getParentFragmentManager().beginTransaction()
                            .replace(R.id.fcv_profile_shower, ContactInfoFragment.class, bundle)
                            .addToBackStack(CONTACT_INFO_F)
                            .commitAllowingStateLoss();
                } catch (Exception ex) {
                    // user may be out of context
                }
            }

        }
    }

    private void showEmailSentAnim() {

        DoneBottomsheetBinding binding = DoneBottomsheetBinding.inflate(getLayoutInflater());

        BottomSheetDialog bsd = new BottomSheetDialog(requireContext(), R.style.BottomSheetDialog);
        bsd.setContentView(binding.getRoot());

        // TODO: 05-07-2023 animation part

        binding.text.setText(getString(R.string.email_sent_to_caregiver));

        binding.subText.setVisibility(View.VISIBLE);
        binding.subText.setText(getString(R.string.continue_and_complete_profile));

        bsd.show();

    }
}
