package com.app.rewardapp.ui.fragments;

import static com.app.rewardapp.adsManager.AdImp.ADCOLONY_REWARD;
import static com.app.rewardapp.adsManager.AdImp.ADMOB_REWARD;
import static com.app.rewardapp.adsManager.AdImp.APPLOVIN_REWARD;
import static com.app.rewardapp.adsManager.AdImp.STARTAPP_REWARD;
import static com.app.rewardapp.adsManager.AdImp.UNITY_REWARD;
import static com.app.rewardapp.adsManager.AdImp.adcolonyAppID;
import static com.app.rewardapp.adsManager.AdImp.adcolonyZoneID;
import static com.app.rewardapp.adsManager.AdImp.admobRewardID;
import static com.app.rewardapp.adsManager.AdImp.applovinRewardID;
import static com.app.rewardapp.adsManager.AdImp.unityRewardID;
import static com.app.rewardapp.util.Constant_Api.Pos;
import static com.app.rewardapp.util.Fun.data;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
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 androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import com.app.rewardapp.Config.Config;
import com.app.rewardapp.R;
import com.app.rewardapp.Responsemodel.CallbackResp;
import com.app.rewardapp.Responsemodel.GameResponse;
import com.app.rewardapp.adapters.GameAdapter;
import com.app.rewardapp.adsManager.RewardAds;
import com.app.rewardapp.databinding.FragmentGamesBinding;
import com.app.rewardapp.listener.OnItemClickListener;
import com.app.rewardapp.restApi.ApiClient;
import com.app.rewardapp.restApi.ApiInterface;
import com.app.rewardapp.adsManager.AdManager;
import com.app.rewardapp.util.Fun;
import com.app.rewardapp.util.Session;

import java.util.ArrayList;
import java.util.List;

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

public class Games extends Fragment implements OnItemClickListener {
    FragmentGamesBinding binding;
    Activity activity;
    GameAdapter adapter;
    List<GameResponse.DataItem> list;
    AdManager adManager;
    String id;
    int pos;
    private static final int REQUEST_CODE = 100;
    public static final String TAG = "GameActivity : ";
    CountDownTimer countDownTimer;
    Session session;
    private AlertDialog dialog, bonus_dialog;
    RewardAds.Builder adNetwork;
    ProgressDialog pb;
    boolean isCredit = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentGamesBinding.inflate(getLayoutInflater());
        activity = getActivity();

        adManager = new AdManager(activity);
        adManager.loadBannerAd(binding.getRoot());
        session = new Session(activity);
        dialog = Fun.loading(activity);

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

        list = new ArrayList<>();
        binding.recyclerViewApps.setLayoutManager(new GridLayoutManager(activity, 2));
        adapter = new GameAdapter(getActivity(), list);
        adapter.setClickListener(this);
        binding.recyclerViewApps.setAdapter(adapter);

        callGame();

        return binding.getRoot();
    }

    private void callGame() {
        Call<GameResponse> call = ApiClient.getClient(getActivity()).create(ApiInterface.class).getGame();
        call.enqueue(new Callback<GameResponse>() {
            @Override
            public void onResponse(Call<GameResponse> call, Response<GameResponse> response) {
                binding.shimmerViewContainer.setVisibility(View.GONE);
                if (response.isSuccessful() && response.body().getSuccess() != 0) {
                    list.addAll(response.body().getData());
                    adapter.notifyDataSetChanged();
                    binding.recyclerViewApps.setVisibility(View.VISIBLE);
                } else {
                    binding.noResult.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<GameResponse> call, Throwable t) {
                binding.shimmerViewContainer.setVisibility(View.GONE);
                binding.noResult.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onClick(View view, int position) {
        loadReward();
        id = list.get(position).getId();
        this.pos = position;
        Pos = position;
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setUrlBarHidingEnabled(true);
        builder.setToolbarColor(getResources().getColor(R.color.colorPrimaryDark));
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.intent.setData(Uri.parse(list.get(position).getLink()));
        startActivityForResult(customTabsIntent.intent, REQUEST_CODE);
        startTime();
    }

    private void loadReward() {
        adNetwork = new RewardAds.Builder(activity);
        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.setInstantReload(true);
        adNetwork.buildAd();
    }


    void startTime() {
        int time = Config.GAME_MINUTE * 60;
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.e(TAG, "onTick: " + (millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                credit();
            }
        }.start();
    }

    void showbonus(String msg, String type) {
        bonus_dialog = new AlertDialog.Builder(activity).setView(LayoutInflater.from(activity).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);
        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 credit() {
        ApiClient.getClient(activity).create(ApiInterface.class).Api(data("", "", "", "", "", "", 14, Integer.parseInt(id), session.Auth())).enqueue(new Callback<CallbackResp>() {
            @Override
            public void onResponse(Call<CallbackResp> call, Response<CallbackResp> response) {
                if (response.isSuccessful() && response.body().getCode() == 201) {
                    isCredit = true;
                    session.setIntData(session.WALLET, response.body().getBalance());
                    Log.e("Game_CREDIT", "onResponse: " + response.body().getMsg());
                }
            }

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


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

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE) {
            Log.e(TAG, "onActivityResult: ");
//            if (isCredit) {
                if (adNetwork.isAdLoaded()) {
                    adNetwork.showReward();
                } else {
                    pb.show();
                    loadReward();
                    new Handler().postDelayed(() -> {
                        pb.dismiss();
                        if (adNetwork.isAdLoaded()) {
                            adNetwork.showReward();
                        }

                    }, 5000);
                }
            }
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}