package com.app.simplitend.caregiverdashboard.fragments;

import static com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity.ACTIVITY_F;
import static com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity.CONTACTS_F;
import static com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity.MED_INFO_F;
import static com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity.MED_REMINDER_F;
import static com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity.WHICH_FRAGMENT;
import static com.app.simplitend.cg_geofencing.CgGeoFencingActivity.GEOFENCE_DETAILS_KEY;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
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 com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.CaregiverDataCache;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.caregiverdashboard.activities.EditProfileInfoActivity;
import com.app.simplitend.caregiverdashboard.activities.PatientProfileShowerActivity;
import com.app.simplitend.caregiverdashboard.mvvm.CaregiverMainViewModel;
import com.app.simplitend.caregiverdashboard.mvvm.CgHomeContracts;
import com.app.simplitend.caregiverdashboard.mvvm.models.GeoFenceDetails;
import com.app.simplitend.cg_geofencing.CgGeoFencingActivity;
import com.app.simplitend.cg_subscription.CgSubscriptionActivity;
import com.app.simplitend.databinding.MyPatientFragmentBinding;
import com.app.simplitend.welcome.welcomecg.mvvm.CareGiverData;
import com.bumptech.glide.Glide;

public class MyPatientFragment extends Fragment implements CgHomeContracts.GetGeoFenceCallback {

    // view binding
    protected MyPatientFragmentBinding binding;

    private CareGiverData careGiverData;

    private CaregiverMainViewModel viewModel;

    private ProgressDialog progressDialog;

    private static MyPatientFragment myPatientFragment;

    public MyPatientFragment() {
        // required empty
    }

    public static synchronized MyPatientFragment getInstance(){
        if (myPatientFragment == null){
            myPatientFragment = new MyPatientFragment();
        }

        return myPatientFragment;
    }

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

        viewModel = new ViewModelProvider(requireActivity()).get(CaregiverMainViewModel.class);
        progressDialog = new ProgressDialog(requireContext());

        adjustLayout();

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        CaregiverDataCache.getCaregiverData(requireContext(), (careGiverData1 -> {
            this.careGiverData = careGiverData1;
            if (careGiverData1 == null || careGiverData1.patientDetails == null) {
                Toast.makeText(requireContext(), "Couldn't load patient details.", Toast.LENGTH_SHORT).show();
                return;
            }

            binding.name.setText(careGiverData1.patientDetails.first_name);
            binding.phoneNumber.setText(careGiverData1.patientDetails.phone_number);

            if (careGiverData1.patientDetails.profile_photo != null){
                Glide.with(requireContext())
                        .load(RetrofitHelper.IMAGE_BASE_URL + careGiverData1.patientDetails.profile_photo)
                        .placeholder(android.R.color.darker_gray)
                        .error(R.drawable.caregiver_img)
                        .into(binding.profileImg);
            }

        }), true);
    }

    // adjusts the guideline percentage w.r.t the aspect ratio of the screen
    private void adjustLayout() {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;

        // Calculate aspect ratio
        float aspectRatio = (float) screenHeight / (float) screenWidth;

        if (aspectRatio < 2.03f) {
            binding.guideline.setGuidelinePercent(0.55f);
        }
    }

    private void initViews() {

    }

    private void clickEvents() {

        binding.peronalInfo.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), EditProfileInfoActivity.class);
            startActivity(intent);
        });

        binding.geofence.setOnClickListener(v -> {
            if (careGiverData != null) {
                progressDialog.setTitle("please wait...");
                progressDialog.setMessage("while we load GeoFence.");
                progressDialog.setCancelable(false);
                progressDialog.show();

                viewModel.getGeoFenceDetails(careGiverData.patientId + "",
                        "",
                        "Bearer " + AppUtil.getCgToken(requireContext()),
                        this);

            } else {
                Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });

        binding.medication.setOnClickListener(v -> {
            gotoProfileShower(MED_REMINDER_F);
        });

        binding.contacts.setOnClickListener(v -> {
            gotoProfileShower(CONTACTS_F);
        });

        binding.medRecords.setOnClickListener(v -> {
            gotoProfileShower(MED_INFO_F);
        });

        binding.patActivities.setOnClickListener(v -> {
            gotoProfileShower(ACTIVITY_F);
        });

        binding.phoneNumber.setOnClickListener(v -> {
            if (careGiverData != null && careGiverData.patientDetails != null) {
                AppUtil.dialPhone(requireActivity(), careGiverData.patientDetails.phone_number);
            }
        });

        binding.subPlans.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), CgSubscriptionActivity.class);
            startActivity(intent);
        });

    }

    private void gotoProfileShower(String which_f) {
        Intent intent = new Intent(requireActivity(), PatientProfileShowerActivity.class);
        intent.putExtra(WHICH_FRAGMENT, which_f);
        startActivity(intent);
    }

    @Override
    public void onGeofenceDetailsFetched(@NonNull GeoFenceDetails geoFenceDetails) {
        progressDialog.dismiss();
        Intent intent = new Intent(requireActivity(), CgGeoFencingActivity.class);
        intent.putExtra(GEOFENCE_DETAILS_KEY, geoFenceDetails);
        startActivity(intent);
    }

    @Override
    public void onGeofenceDetailsFetchFailed(Throwable throwable, String message) {
        progressDialog.dismiss();
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }
}
