package com.retrytech.strangerapp.activity;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;

import com.android.billingclient.api.BillingClient;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.adapter.CoinPackageAdapter;
import com.retrytech.strangerapp.databinding.ActivityWalletBinding;
import com.retrytech.strangerapp.modal.coinpackage.CoinPackages;
import com.retrytech.strangerapp.modal.settings.AppSettings;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;
import com.retrytech.strangerapp.utils.MyPlayStoreBilling;
import com.retrytech.strangerapp.utils.SessionManager;
import com.retrytech.strangerapp.utils.ads.MyRewardAds;

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

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

public class WalletActivity extends AppCompatActivity {

    ActivityWalletBinding binding;
    SessionManager sessionManager;
    CoinPackageAdapter adapter;
    List<CoinPackages.Data> packagesList = new ArrayList<>();
    MyPlayStoreBilling myPlayStoreBilling;
    int coinAmount = 0;
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
            return defaultInsets.replaceSystemWindowInsets(
                    defaultInsets.getSystemWindowInsetLeft(),
                    0,
                    defaultInsets.getSystemWindowInsetRight(),
                    defaultInsets.getSystemWindowInsetBottom());
        });
        ViewCompat.requestApplyInsets(decorView);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        binding = DataBindingUtil.setContentView(this, R.layout.activity_wallet);
        adapter = new CoinPackageAdapter();
        sessionManager = new SessionManager(this);
        binding.tvCoinPlans.setText(String.valueOf(sessionManager.getAppSettings().getGender().getRewardedAdsReward()).concat(" ").concat(getResources().getString(R.string.coins)));
        myPlayStoreBilling = new MyPlayStoreBilling(this, new MyPlayStoreBilling.OnPurchaseComplete() {
            @Override
            public void onConnected(boolean isConnect) {

            }

            @Override
            public void onPurchaseResult(boolean isPurchaseSuccess) {
                if (isPurchaseSuccess) {
                    Toast.makeText(WalletActivity.this, "Success", Toast.LENGTH_SHORT).show();
                    addCoinToUserAccount();
                }
            }

            @Override
            public void onError(boolean hasError) {

            }
        });
        binding.recyclerview.setAdapter(adapter);
        binding.imgBack.setOnClickListener(view -> onBackPressed());
        binding.tvCoins.setText(String.valueOf(sessionManager.getUser().getData().getCoins()));

        dialog = new Dialog(this);
        View dialogueView = LayoutInflater.from(this).inflate(R.layout.item_loader, null, false);
        dialog.setContentView(dialogueView);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, android.R.color.transparent)));

        fetchPackages();

        binding.btnContinue.setOnClickListener(view -> {
            Log.d("TAG", "onCreate: " + adapter.getLastPositionData().getAmount());
            coinAmount = Integer.parseInt(adapter.getLastPositionData().getAmount());
            myPlayStoreBilling.startPurchase(adapter.getLastPositionData().getPlayid(), BillingClient.SkuType.INAPP, true);
        });
        MyRewardAds myRewardAds = new MyRewardAds(this);
        myRewardAds.setRewardAdListnear(new MyRewardAds.RewardAdListnear() {
            @Override
            public void onAdClosed() {

            }

            @Override
            public void onEarned() {
                coinAmount = sessionManager.getAppSettings().getGender().getRewardedAdsReward();
                addCoinToUserAccount();
            }
        });
        binding.rewardAds.setOnClickListener(v -> {
            myRewardAds.showAd();
        });

    }

    private void addCoinToUserAccount() {
        Call<AppSettings> call = RetrofitClient.getService().addCoins(Const.API_KEY, sessionManager.getUser().getData().getId(), coinAmount);
        call.enqueue(new Callback<AppSettings>() {
            @Override
            public void onResponse(Call<AppSettings> call, Response<AppSettings> response) {
                if (response.body() != null) {
                    AppSettings settings = response.body();
                    if (settings.isStatus()) {
                        sessionManager.manageWallet(true, coinAmount);
                        binding.tvCoins.setText(String.valueOf(sessionManager.getUser().getData().getCoins()));
                    }
                }
            }

            @Override
            public void onFailure(Call<AppSettings> call, Throwable t) {
                Toast.makeText(WalletActivity.this, getResources().getString(R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void fetchPackages() {
        dialog.show();
        Call<CoinPackages> call = RetrofitClient.getService().fetchCoinPackages(Const.API_KEY);
        call.enqueue(new Callback<CoinPackages>() {
            @Override
            public void onResponse(Call<CoinPackages> call, Response<CoinPackages> response) {
                if (response.body() != null) {
                    CoinPackages packages = response.body();
                    packagesList = packages.getData();
                    adapter.updateData(packagesList);
                    dialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<CoinPackages> call, Throwable t) {
                Toast.makeText(WalletActivity.this, getResources().getString(R.string.something_went_wrong), Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
    }
}