package com.app.simplitend.caregiverdashboard.activities;

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.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
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.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.databinding.ActivityCgProfileProgressBinding;
import com.app.simplitend.welcome.welcomecg.mvvm.CareGiverData;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

public class CgProfileProgressActivity extends AppCompatActivity implements CgHomeContracts.GetGeoFenceCallback {

    // view binding
    protected ActivityCgProfileProgressBinding binding;

    private CareGiverData careGiverData;

    private CaregiverMainViewModel viewModel;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCgProfileProgressBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

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

        Glide.with(this)
                .asGif()
                .load(R.raw.done_anim_primary)
                .listener(new RequestListener<GifDrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (resource == null) return false;

                        resource.setLoopCount(1);
                        return false;
                    }
                })
                .into(binding.animIv);

        binding.linkBtn.setOnClickListener(v -> {
            binding.paySuccessCompleteView.setVisibility(View.GONE);
            binding.loadingView.setVisibility(View.VISIBLE);
            syncPatientData();
        });

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void syncPatientData() {
        startAnimation();

        new Handler().postDelayed(() -> {
            CaregiverDataCache.getCaregiverData(this, (careGiverData1 -> {
                this.careGiverData = careGiverData1;

                binding.loadingView.setVisibility(View.GONE);
                binding.profileProgressView.setVisibility(View.VISIBLE);

                initViews();

                clickEvents();
            }), false);
        }, 3000);
    }

    private void startAnimation() {
        Glide.with(this)
                .asGif()
                .load(R.raw.ic_sync_data)
                .into(binding.loadingAnim);
    }

    private void clickEvents() {
        binding.skipToDash.setOnClickListener(v -> {
            Intent intent = new Intent(this, CaregiverDashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        });

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

        binding.geoFencing.setOnClickListener(v -> {
            progressDialog.setTitle("please wait...");
            progressDialog.setMessage("while we load GeoFence.");
            progressDialog.setCancelable(false);
            progressDialog.show();

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

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

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

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

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

        binding.fua.setOnClickListener(v -> {
            AppUtil.showAlert(this,
                    "App Whitelist",
                    "You can whitelist app from the patient's device.",
                    getString(R.string.ok),
                    ((dialogInterface, i) -> {}),
                    null, null);
        });

    }

    private void initViews() {
        if (careGiverData == null || careGiverData.patientDetails == null){
            Toast.makeText(this, "Something went wrong.", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.title.setText(careGiverData.patientDetails.first_name);
    }

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

    @Override
    public void onGeofenceDetailsFetched(GeoFenceDetails geoFenceDetails) {
        progressDialog.dismiss();
        try {
            Intent intent = new Intent(this, CgGeoFencingActivity.class);
            intent.putExtra(GEOFENCE_DETAILS_KEY, geoFenceDetails);
            startActivity(intent);
        } catch (Exception e) {
            // do nothing
        }
    }

    @Override
    public void onGeofenceDetailsFetchFailed(Throwable throwable, String message) {
        progressDialog.dismiss();
        try {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            // do nothing
        }
    }
}