package com.app.simplitend.patientprofile;

import static com.app.simplitend.apputils.NotificationService.CONTENT_TYPE_KEY;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
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.vectordrawable.graphics.drawable.Animatable2Compat;

import com.app.simplitend.apputils.Constants;
import com.app.simplitend.apputils.PatientDataCache;
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;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.databinding.RegisterationDoneFragmentBinding;
import com.app.simplitend.patient_dashboard.DashBoardActivity;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.CallResponse;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.PatientData;
import com.onesignal.OneSignal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterCompleteFragment extends Fragment implements ProfileContracts.ProfileProgressCallback{

    public RegisterationDoneFragmentBinding binding;

    public static final String PROFILE_PROGRESS = "profile_progress";
    public static final String IS_CONNECTED_TO_CG = "is_connect_to_cg";

    int profile_progress, is_connect_to_caregiver;

    private ProgressDialog progressDialog;

    private BroadcastReceiver notification_receiver;

    public RegisterCompleteFragment() {
        // required
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = RegisterationDoneFragmentBinding.inflate(inflater, container, false);
        progressDialog = new ProgressDialog(requireContext());

        if (getArguments() != null) {
            profile_progress = getArguments().getInt(PROFILE_PROGRESS, 20);
            is_connect_to_caregiver = getArguments().getInt(IS_CONNECTED_TO_CG, 0);
        }

        Glide.with(requireContext())
                .asGif()
                .load(R.raw.filling_anim)
                .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);
                        resource.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
                            @Override
                            public void onAnimationEnd(Drawable drawable) {
                                super.onAnimationEnd(drawable);
                                String title = "Your profile is " + (profile_progress * 20) + "% complete!";

                                binding.title.setText(title);
                                YoYo.with(Techniques.FadeIn)
                                        .duration(100)
                                        .playOn(binding.title);
                            }
                        });
                        return false;
                    }
                })
                .into(binding.animIv);

        binding.proceed.setOnClickListener(v -> {
            checkConnectionStatus();
        });

        notification_receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String content_type = intent.getStringExtra(CONTENT_TYPE_KEY);

                if (Constants.NEW_SUBSCRIPTION.equals(content_type)){
                    // new subscription was bought by caregiver
                    // updating patient data cache
                    PatientDataCache.setPatientData(null); // to load new instance of data
                    PatientDataCache.getPatientData(requireContext(), patientData -> {
                        if (patientData == null){
                            Toast.makeText(requireContext(), "Couldn't connect", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        gotoPatientDashBoard();
                    }, true);

                }
            }
        };

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        requireContext().registerReceiver(notification_receiver, new IntentFilter(AppUtil.NOTIFICATION_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();
        requireContext().unregisterReceiver(notification_receiver);
    }

    private void checkConnectionStatus() {
        progressDialog = new ProgressDialog(requireContext());
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("while we check the Caregiver connection status.");
        progressDialog.setCancelable(false);
        progressDialog.show();

        PatientProfileAPIService apiService = RetrofitHelper.getRetrofit().create(PatientProfileAPIService.class);

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

        String sub_id = OneSignal.getUser().getPushSubscription().getId() + "";

        apiService.getUsrProfileProgress(token, sub_id, AppUtil.getTimeZone())
                .enqueue(new Callback<CallResponse<PatientData>>() {
                    @Override
                    public void onResponse(Call<CallResponse<PatientData>> call, Response<CallResponse<PatientData>> response) {
                        if (response.body() != null) {
                            if (response.body().status != 200 || response.body().result == null) {
                                onProfileProgressFetchFailed(new Exception(), response.body().message);
                                return;
                            }

                            // updating patient data cache
                            PatientDataCache.setPatientData(response.body().result);

                            onProfileProgressFetched(response.body().result);
                        } else {
                            onProfileProgressFetchFailed(new Exception(), "Please try again later.");
                        }
                    }

                    @Override
                    public void onFailure(Call<CallResponse<PatientData>> call, Throwable t) {
                        onProfileProgressFetchFailed(new Exception(), "Please try again later.");
                    }
                });
    }

    private void gotoPatientDashBoard() {
        Intent intent = new Intent(requireActivity(), DashBoardActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        requireActivity().finish();
    }

    @Override
    public void onProfileProgressFetched(PatientData patientData) {
        progressDialog.dismiss();

        if (patientData.isCareGiverConnectedWithPatient == 1) {
            if (patientData.isCaregiverTakeSubscription == 1){
                gotoPatientDashBoard();
            }else{
                AppUtil.showAlert(requireContext(),
                        "Kindly ask Caregiver to subscribe",
                        "Once your caregiver has completed the " +
                                "subscription, you will be able to use the " +
                                "application.",
                        "OK",
                        ((dialogInterface, i) -> {

                        }), null, null);
            }
        } else {
            AppUtil.showAlert(requireContext(),
                    "Kindly ask Caregiver to complete registration",
                    "Once your caregiver has completed the " +
                            "registration, you will be able to use the " +
                            "application.",
                    "OK",
                    ((dialogInterface, i) -> {

                    }), null, null);
        }
    }

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

//binding.animIv.setAnimation(R.raw.done_anim_2);
//        binding.animIv.playAnimation();
//
//        binding.animIv.addAnimatorListener(new Animator.AnimatorListener() {
//@Override
//public void onAnimationStart(@NonNull Animator animator) {
//
//        }
//
//@Override
//public void onAnimationEnd(@NonNull Animator animator) {
//
//        String title = "Your profile is " + (profile_progress * 20) + "% complete!";
//
//        binding.title.setText(title);
//        YoYo.with(Techniques.FadeIn)
//        .duration(100)
//        .playOn(binding.title);
//        }
//
//@Override
//public void onAnimationCancel(@NonNull Animator animator) {
//
//        }
//
//@Override
//public void onAnimationRepeat(@NonNull Animator animator) {
//
//        }
//        });
