package com.app.rewardapp.ui.fragments;

import static com.app.rewardapp.util.Fun.data;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.app.rewardapp.R;
import com.app.rewardapp.Responsemodel.BannerResponse;
import com.app.rewardapp.Responsemodel.CallbackResp;
import com.app.rewardapp.Responsemodel.OfferResponse;
import com.app.rewardapp.adapters.SliderAdapterExample;
import com.app.rewardapp.adsManager.RewardAds;
import com.app.rewardapp.databinding.FragmentHomeNewBinding;
import com.app.rewardapp.restApi.ApiClient;
import com.app.rewardapp.restApi.ApiInterface;
import com.app.rewardapp.ui.activity.MathQuiz;
import com.app.rewardapp.ui.activity.ScratchActivity;
import com.app.rewardapp.ui.activity.SpinActivity;
import com.app.rewardapp.ui.activity.WeburlActivity;
import com.app.rewardapp.ui.activity.WithdrawActivity;
import com.app.rewardapp.adsManager.AdImp;
import com.app.rewardapp.adsManager.AdManager;
import com.app.rewardapp.util.Constant_Api;
import com.app.rewardapp.util.Fun;
import com.app.rewardapp.util.Session;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;

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

public class HomeNew extends Fragment implements AdImp {
    FragmentHomeNewBinding binding;
    Session session;
    private AlertDialog bonus_dialog;
    AlertDialog dialog;
    RewardAds.Builder adNetwork;
    AdManager adManager;
    private ReviewManager reviewManager;
    ProgressDialog pb;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding =FragmentHomeNewBinding.inflate(getLayoutInflater());
        session = new Session(getActivity());
        dialog= Fun.loading(getActivity());
        getActivity().findViewById(R.id.navigation).setVisibility(View.VISIBLE);
        adManager=new AdManager(getActivity());

        pb = new ProgressDialog(getActivity());
        pb.setMessage(getString(R.string.loading));
        pb.setCancelable(false);

        fetchOffer();
        loadReward();
        inAppReview();

        bonus_dialog = new AlertDialog.Builder(getActivity()).setView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_collect_bonus, null)).create();
        bonus_dialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        bonus_dialog.getWindow().setWindowAnimations(R.style.Dialoganimation);
        bonus_dialog.setCanceledOnTouchOutside(false);

        slideBanner();

        binding.lytDaily.setOnClickListener(v -> {
            if (adNetwork.isAdLoaded()) {
                adNetwork.showReward();
            } else {
                pb.show();
                loadReward();
                new Handler().postDelayed(() -> {
                    pb.dismiss();
                    if (adNetwork.isAdLoaded()) {
                        adNetwork.showReward();
                    } else {
                        Toast.makeText(getActivity(), "Try Again No ads Available", Toast.LENGTH_SHORT).show();
                    }
                }, 5000);
            }
        });
        binding.lytSpin.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            startActivity(new Intent(getActivity(), SpinActivity.class));
        });
        binding.lytArticle.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            startActivity(new Intent(getActivity(), WeburlActivity.class));
        });

        binding.lytScratch.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            startActivity(new Intent(getActivity(), ScratchActivity.class));
        });

        binding.lytVideo.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            loadFragment(new Video());
        });

        binding.lytOffer.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            loadFragment(new Task());
        });

        binding.lytReward.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            startActivity(new Intent(getActivity(), WithdrawActivity.class));
        });


        binding.lytQuiz.setOnClickListener(v -> {
            adManager.loadInterstitalAd();
            startActivity(new Intent(getActivity(), MathQuiz.class));
        });


        return binding.getRoot();
    }

    private void showDialog() {
        dialog.show();
    }

    private void dismissDialog() {
        if(dialog.isShowing()){
            dialog.dismiss();
        }
    }


    private void dailycheckin() {
        showDialog();
        ApiClient.getClient(getActivity()).create(ApiInterface.class).Api(data("","","","","","",3,0,session.Auth())).enqueue(new Callback<CallbackResp>() {
            @Override
            public void onResponse(Call<CallbackResp> call, Response<CallbackResp> response) {
                dismissDialog();
                if(response.isSuccessful() && response.body().getCode()==201){
                    session.setIntData(session.WALLET,response.body().getBalance());
                    showbonus(response.body().getMsg(),"");
                }else {
                    try {
                        showbonus(response.body().getMsg(),"error");
                    }catch (Exception e){

                    }
                }
            }

            @Override
            public void onFailure(Call<CallbackResp> call, Throwable t) {
                dismissDialog();
            }
        });
    }

    void showbonus(String msg, String type){
        bonus_dialog.show();
        TextView tv,congrats;
        tv=bonus_dialog.findViewById(R.id.txt);
        congrats=bonus_dialog.findViewById(R.id.congrts);
        tv.setText(msg);
        if(type.equals("error")){
            congrats.setText(getString(R.string.oops));
            congrats.setTextColor(getResources().getColor(R.color.red));
        }
        bonus_dialog.findViewById(R.id.closebtn).setOnClickListener(view -> {bonus_dialog.dismiss();});
    }

    private void loadFragment(Fragment fragment) {
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.commit();
    }


    @Override
    public void onResume() {
        if(adNetwork.isCompleted()){
            adNetwork.setCompleted(false);
            dailycheckin();
        }else{
            loadReward();
        }
        super.onResume();
    }

    private void loadReward() {
        adNetwork= new RewardAds.Builder(getActivity());
        adNetwork.setAdcolony_Appid(adcolonyAppID);
        adNetwork.setAdcolonyZone(adcolonyZoneID);
        adNetwork.setAdmob_au(admobRewardID);
        adNetwork.setMax_au(applovinRewardID);
        adNetwork.setUnity_au(unityRewardID);
        adNetwork.setAdmob_reward(ADMOB_REWARD);
        adNetwork.setAdcolony_reward(ADCOLONY_REWARD);
        adNetwork.setApplovin_reward(APPLOVIN_REWARD);
        adNetwork.setStatartapp_reward(STARTAPP_REWARD);
        adNetwork.setUnity_reward(UNITY_REWARD);
        adNetwork.setRewardMode(true);
        adNetwork.buildAd();
    }


    private void slideBanner() {
        SliderView sliderView = binding.imageSlider;
        sliderView.setIndicatorAnimation(IndicatorAnimationType.WORM); //set indicator animation by using IndicatorAnimationType. :WORM or THIN_WORM or COLOR or DROP or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP!!
        sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
        sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
        sliderView.setIndicatorSelectedColor(Color.WHITE);
        sliderView.setIndicatorUnselectedColor(Color.GRAY);
        sliderView.setScrollTimeInSec(4);
        sliderView.startAutoCycle();
        Call<BannerResponse> call = ApiClient.getClient(getActivity()).create(ApiInterface.class).SLideBanner();
        call.enqueue(new Callback<BannerResponse>() {
            @Override
            public void onResponse(Call<BannerResponse> call, Response<BannerResponse> response) {
                if (response.isSuccessful() && response.body().getData().size() != 0) {
                    SliderAdapterExample adapter = new SliderAdapterExample(getActivity(),response.body().getData());
                    sliderView.setSliderAdapter(adapter);
                }else {
                    binding.cvbanner.setVisibility(View.GONE);
                }
            }
            @Override
            public void onFailure(Call<BannerResponse> call, Throwable t) {
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void fetchOffer() {
        if (Constant_Api.Task.size() == 0) {
            showDialog();
            ApiClient.getClient(getActivity()).create(ApiInterface.class).getOffers().enqueue(new Callback<OfferResponse>() {
                @Override
                public void onResponse(Call<OfferResponse> call, Response<OfferResponse> response) {
                    dismissDialog();
                    if (response.isSuccessful() && response.body().getCode() == 201) {
                        Constant_Api.Task = response.body().getData();
                        checkTask();
                    }

                }
                @Override
                public void onFailure(Call<OfferResponse> call, Throwable t) {
                    Log.e("offerResp", "onFailure: " + t.getMessage());
                    dismissDialog();
                }
            });
        } else {
            checkTask();
        }
    }

    void checkTask(){
        if(Constant_Api.Task.size()>0){
            if (Constant_Api.Task.get(0).getStatus() == 1) {
                binding.lytDaily.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(1).getStatus() == 1) {
                binding.lytSpin.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(2).getStatus() == 1) {
                binding.lytArticle.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(3).getStatus() == 1) {
                binding.lytVideo.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(4).getStatus() == 1) {
                binding.lytOffer.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(5).getStatus() == 1) {
                binding.lytReward.setVisibility(View.GONE);
            }
            if (Constant_Api.Task.get(6).getStatus() == 1) {
                binding.lytQuiz.setVisibility(View.GONE);
            }
        }
    }

    void inAppReview(){
        reviewManager = ReviewManagerFactory.create(getActivity());
        com.google.android.play.core.tasks.Task<ReviewInfo> request = reviewManager.requestReviewFlow();
        request.addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                // Getting the ReviewInfo object
                ReviewInfo reviewInfo = task.getResult();
                com.google.android.play.core.tasks.Task<Void> flow = reviewManager.launchReviewFlow(getActivity(), reviewInfo);
                flow.addOnCompleteListener(task1 -> {

                });
            }
        });
    }
}
