package com.app.simplitend.patientprofile.medicalinfo;

import static com.app.simplitend.patientprofile.medicalinfo.AddMedicalInfoFragment.MEDICAL_INFO_KEY;

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 com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.databinding.MedicalIntoFragmentBinding;
import com.app.simplitend.patientprofile.ProfileContracts;
import com.app.simplitend.patientprofile.medicalinfo.mvvm.MedicalInfoViewModel;
import com.app.simplitend.patientprofile.medicalinfo.mvvm.MedicationInfo;

public class MedicalInfoFragment extends Fragment implements ProfileContracts.GetMedicationInfoCallback {

    // view binding
    protected MedicalIntoFragmentBinding binding;

    private MedicalInfoViewModel medicalInfoViewModel;

    private ProgressDialog progressDialog;

    private MedicationInfo medicationInfo;

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = MedicalIntoFragmentBinding.inflate(inflater, container, false);
        medicalInfoViewModel = new ViewModelProvider(requireActivity()).get(MedicalInfoViewModel.class);

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {
        progressDialog = new ProgressDialog(requireContext());

        // loading medical info
        progressDialog.setTitle("Please wait..");
        progressDialog.setMessage("while we load your medical information.");
        progressDialog.setCancelable(false);
        progressDialog.show();

        String token = "Bearer " + AppUtil.getPatientToken(requireContext());

        medicalInfoViewModel.getMedicalInfo(AppUtil.getPatientUid(requireContext()),
                token, this);
    }

    private void clickEvents() {

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

        binding.addMedInfo.setOnClickListener(v -> {

                    try {
                        Navigation.findNavController(v).navigate(R.id.action_medicalInfoFragment_to_addMedicalInfoFragment);
                    } catch (Exception e) {
                        // there may be a IllegalStateException as this same fragment is used from another fragment
                        // and not through the nav graph

                        try {
                            getParentFragmentManager().beginTransaction()
                                    .replace(R.id.fcv_profile_shower, AddMedicalInfoFragment.class, null)
                                    .addToBackStack("add_reminder")
                                    .commitAllowingStateLoss();
                        } catch (Exception ex) {
                            // user may be out of context
                        }
                    }
                }
        );

        binding.editBtn.setOnClickListener(v -> {

            if (medicationInfo != null) {
                Bundle bundle = new Bundle();

                bundle.putSerializable(MEDICAL_INFO_KEY, medicationInfo);

                try {
                    Navigation.findNavController(v).navigate(R.id.action_medicalInfoFragment_to_addMedicalInfoFragment, bundle);
                }catch (Exception e){
                    // there may be a IllegalStateException as this same fragment is used from another fragment
                    // and not through the nav graph

                    try {
                        getParentFragmentManager().beginTransaction()
                                .replace(R.id.fcv_profile_shower, AddMedicalInfoFragment.class, bundle)
                                .addToBackStack("add_reminder")
                                .commitAllowingStateLoss();
                    } catch (Exception ex) {
                        // user may be out of context
                    }
                }
            }

        });

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

    }

    private void loadMedicalInfo(MedicationInfo medicationInfo) {
        binding.diagnosis.setText(medicationInfo.diagnosis);
        binding.primaryDoc.setText(medicationInfo.primary_care_doctor);
        binding.docContact.setText(medicationInfo.doctor_phone_number);
        binding.hospitalPref.setText(medicationInfo.hospital_preference);
        binding.allergies.setText(medicationInfo.allergies);
        binding.dietRestrict.setText(medicationInfo.diet_restriction);
    }

    @Override
    public void onMedicalInfoFetched(MedicationInfo medicationInfo) {
        this.medicationInfo = medicationInfo;
        progressDialog.dismiss();

        if (medicationInfo != null) {
            binding.medicalInfo.setVisibility(View.VISIBLE);
            binding.noData.setVisibility(View.GONE);
            binding.addMedInfo.setVisibility(View.GONE);
            binding.editBtn.setVisibility(View.VISIBLE);

            loadMedicalInfo(medicationInfo);
        } else {
            binding.noData.setVisibility(View.VISIBLE);
            binding.medicalInfo.setVisibility(View.GONE);
            binding.addMedInfo.setVisibility(View.VISIBLE);
            binding.editBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void onMedicationInfoFetchedFailed(Throwable t, String message) {
        progressDialog.dismiss();

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