package com.ElyStudio.leGaou.activities;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.databinding.ActivityQuizResultScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.AppCompat;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;

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

public class QuizResultScreen extends AppCompat {

    ActivityQuizResultScreenBinding binding;
    int score,totalQuestions,questionAttempted,correctAnswers,wrongAnswers;
    float prizePerQuestion;
    int prize,bonus;
    String quizName,quizIcon;
    int quizColor;
    int quizEntryFee;
    public static final String TAG = "QUIZ_RESULT_SCREEN";

    private RewardedAd mRewardedAd;
    private InterstitialAd mInterstitialAd;
    int adEnabled;
    String nativeAdId,interstitialAdId,rewardedAdId;
    BottomSheetDialog noInternetBottomSheet;

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

        getResultData();
        setUpScoreCard();
        prize = (int) (prizePerQuestion * correctAnswers);
        bonus = (int) (prize * 0.25);
        String quizTitle = quizName+' '+getResources().getString(R.string.result);
        String userPrize = getResources().getString(R.string.you_won)+' '+prize;
        String bonusCoins = getResources().getString(R.string.claim)+" +"+bonus;
        binding.resultTitle.setText(quizTitle);
        binding.userPrize.setText(userPrize);
        binding.bonusCoin.setText(bonusCoins);

        binding.bonusCoinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.bonusCoinButton.setVisibility(View.GONE);
                binding.adProgressBar.setVisibility(View.VISIBLE);
                loadRewardedAd();
            }
        });

        binding.claimPrizeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getQuizPrize();
            }
        });


    }

    @Override
    protected void onStart() {
        super.onStart();
        getResultData();
        loadNativeAd(binding.adPlaceHolderLayout);
        loadInterstitialAd();
    }

    public void getResultData(){

        adEnabled = getIntent().getIntExtra(Constants.adEnabled,0);
        nativeAdId = getIntent().getStringExtra(Constants.nativeAdId);
        interstitialAdId = getIntent().getStringExtra(Constants.interstitialAdId);
        rewardedAdId = getIntent().getStringExtra(Constants.rewardedAdId);

        quizName = getIntent().getStringExtra(Constants.quizName);
        quizIcon = getIntent().getStringExtra(Constants.quizIcon);
        quizColor = getIntent().getIntExtra(Constants.quizColorCode,0);
        quizEntryFee = getIntent().getIntExtra(Constants.quizEntryFee,0);

        score = getIntent().getIntExtra(Constants.userScore,0);
        totalQuestions = getIntent().getIntExtra(Constants.quizQuestionLimit,0);
        questionAttempted = getIntent().getIntExtra(Constants.quizQuestionAttempted,0);
        correctAnswers = getIntent().getIntExtra(Constants.quizCorrectAnswers,0);
        wrongAnswers = getIntent().getIntExtra(Constants.quizWrongAnswers,0);
        prizePerQuestion = getIntent().getFloatExtra(Constants.quizPrizePerQuestion,0);
    }

    public void setUpScoreCard(){

        binding.questionAttemptedProgressBar.setMax(totalQuestions);
        binding.correctAnswerProgressBar.setMax(questionAttempted);
        binding.wrongAnswerProgressBar.setMax(questionAttempted);
        binding.questionAttempted.setText(String.valueOf(questionAttempted));
        binding.correctAnswers.setText(String.valueOf(correctAnswers));
        binding.wrongAnswers.setText(String.valueOf(wrongAnswers));
        binding.userScore.setText(String.valueOf(score));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            binding.questionAttemptedProgressBar.setProgress(questionAttempted,true);
            binding.correctAnswerProgressBar.setProgress(correctAnswers,true);
            binding.wrongAnswerProgressBar.setProgress(wrongAnswers,true);
        }
        else
        {
            binding.questionAttemptedProgressBar.setProgress(questionAttempted);
            binding.correctAnswerProgressBar.setProgress(correctAnswers);
            binding.wrongAnswerProgressBar.setProgress(wrongAnswers);
        }

    }

    public void loadRewardedAd(){

        if(rewardedAdId == null)
        {
            adEnabled = getIntent().getIntExtra(Constants.adEnabled,0);
            rewardedAdId = getIntent().getStringExtra(Constants.rewardedAdId);
        }

        if(adEnabled == 1)
        {
            AdRequest adRequest = new AdRequest.Builder().build();

            RewardedAd.load(QuizResultScreen.this, rewardedAdId, adRequest, new RewardedAdLoadCallback() {
                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    super.onAdFailedToLoad(loadAdError);
                    mRewardedAd = null;
                    binding.bonusCoinButton.setVisibility(View.VISIBLE);
                    binding.adProgressBar.setVisibility(View.GONE);
                    QuizzeSnackBar.showSnackBar(QuizResultScreen.this, binding.getRoot(), getResources().getString(R.string.no_ads_available), getResources().getColor(R.color.error));
                }

                @Override
                public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                    super.onAdLoaded(rewardedAd);
                    mRewardedAd = rewardedAd;
                    mRewardedAd.show(QuizResultScreen.this, new OnUserEarnedRewardListener() {
                        @Override
                        public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                            prize = prize + bonus;
                            String userPrizeWon = getResources().getString(R.string.you_won) + ' ' + prize;
                            binding.userPrize.setText(userPrizeWon);
                            binding.bonusCoinButton.setVisibility(View.GONE);
                            binding.adProgressBar.setVisibility(View.GONE);
                        }
                    });
                }
            });
        }
        else
        {
            binding.bonusCoinButton.setVisibility(View.VISIBLE);
            binding.adProgressBar.setVisibility(View.GONE);
            QuizzeSnackBar.showSnackBar(QuizResultScreen.this,binding.getRoot(),getResources().getString(R.string.no_ads_available),getResources().getColor(R.color.error));
        }

    }

    public void loadNativeAd(FrameLayout frameLayout){

        if(nativeAdId == null)
        {
            adEnabled = getIntent().getIntExtra(Constants.adEnabled,0);
            nativeAdId = getIntent().getStringExtra(Constants.nativeAdId);
        }

        if(adEnabled == 1)
        {

            AdLoader.Builder builder = new AdLoader.Builder(QuizResultScreen.this, nativeAdId);

            builder.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
                @Override
                public void onNativeAdLoaded(@NonNull NativeAd nativeAd) {

                    NativeAdView nativeAdView = (NativeAdView) getLayoutInflater().inflate(R.layout.medium_native_ad_layout, null);
                    populateNativeAd(nativeAd, nativeAdView);

                    frameLayout.removeAllViews();
                    frameLayout.addView(nativeAdView);
                }
            });


            AdLoader adLoader = builder.withAdListener(new AdListener() {
                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    super.onAdFailedToLoad(loadAdError);
                    Log.d(TAG, "Failed to load interstitial ad = " + loadAdError);
                }

                @Override
                public void onAdLoaded() {
                    super.onAdLoaded();
                }
            }).build();

            adLoader.loadAd(new AdRequest.Builder().build());

        }


    }

    public void populateNativeAd(NativeAd nativeAd,NativeAdView nativeAdView){

        nativeAdView.setHeadlineView(nativeAdView.findViewById(R.id.adHeadlineMedium));
        nativeAdView.setIconView(nativeAdView.findViewById(R.id.adIconMedium));
        nativeAdView.setBodyView(nativeAdView.findViewById(R.id.adBodyMedium));
        nativeAdView.setCallToActionView(nativeAdView.findViewById(R.id.callToActionButtonMedium));
        nativeAdView.setAdvertiserView(nativeAdView.findViewById(R.id.adAdvertiserMedium));

        ((TextView) nativeAdView.getHeadlineView()).setText(nativeAd.getHeadline());

        if(nativeAd.getIcon() == null)
        {
            nativeAdView.getIconView().setVisibility(View.INVISIBLE);
        }
        else
        {
            nativeAdView.getIconView().setVisibility(View.VISIBLE);
            ((ImageView) nativeAdView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
        }

        if(nativeAd.getBody() == null)
        {
            nativeAdView.getBodyView().setVisibility(View.INVISIBLE);
        }
        else
        {
            nativeAdView.getBodyView().setVisibility(View.VISIBLE);
            ((TextView) nativeAdView.getBodyView()).setText(nativeAd.getBody());
        }

        if(nativeAd.getCallToAction() == null)
        {
            nativeAdView.getCallToActionView().setVisibility(View.INVISIBLE);
        }
        else
        {
            nativeAdView.getCallToActionView().setVisibility(View.VISIBLE);
            ((Button) nativeAdView.getCallToActionView()).setText(nativeAd.getCallToAction());
        }

        if(nativeAd.getAdvertiser() == null)
        {
            nativeAdView.getAdvertiserView().setVisibility(View.INVISIBLE);
        }
        else
        {
            nativeAdView.getAdvertiserView().setVisibility(View.VISIBLE);
            ((TextView) nativeAdView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
        }

        nativeAdView.setNativeAd(nativeAd);

    }

    public void loadInterstitialAd(){

        if(adEnabled == 1)
        {
            AdRequest adRequest = new AdRequest.Builder().build();

            InterstitialAd.load(QuizResultScreen.this, interstitialAdId, adRequest, new InterstitialAdLoadCallback() {
                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    super.onAdFailedToLoad(loadAdError);
                    Log.d(TAG,"Failed to load interstitial ad  = "+loadAdError);
                }

                @Override
                public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                    super.onAdLoaded(interstitialAd);
                    mInterstitialAd = interstitialAd;
                }
            });
        }

    }

    public void showInterstitialAd(){

        binding.claimPrizeButton.setVisibility(View.GONE);
        binding.quizResultProgressBar.setVisibility(View.VISIBLE);

        if(interstitialAdId == null)
        {
            adEnabled = getIntent().getIntExtra(Constants.adEnabled,0);
            interstitialAdId = getIntent().getStringExtra(Constants.interstitialAdId);
        }

        if(mInterstitialAd != null) {

            mInterstitialAd.show(QuizResultScreen.this);

            mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                @Override
                public void onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent();
                    startActivity(new Intent(QuizResultScreen.this, MainActivity.class));
                    finish();
                }
            });
        }
        else
        {
            startActivity(new Intent(QuizResultScreen.this, MainActivity.class));
            finish();
        }


    }

    private void getQuizPrize(){

        String quizHistoryActivity = quizName+' '+getResources().getString(R.string.prize);
        if(quizIcon == null)
        {
            quizIcon = "";
        }

        if(CheckInternetConnection.isInternetConnected(QuizResultScreen.this))
        {
            Call<ApiResponse> getQuizPrizeCall = ApiController.getInstance().getApi().getQuizPrize(FirebaseAuth.getInstance().getUid(),quizName,quizIcon,quizColor,totalQuestions,questionAttempted,correctAnswers,wrongAnswers,quizEntryFee,prize,quizHistoryActivity);

            getQuizPrizeCall.enqueue(new Callback<ApiResponse>() {
                @Override
                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        showInterstitialAd();
                    }
                    else
                    {
                        Log.d(TAG,"getQuizPrizeCall Response = "+response.body().getMessage());
                        QuizzeSnackBar.showSnackBar(QuizResultScreen.this,binding.getRoot(),getResources().getString(R.string.internal_error),getResources().getColor(R.color.error));
                        startActivity(new Intent(QuizResultScreen.this,MainActivity.class));
                        finish();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse> call, Throwable t) {
                    Log.d(TAG,"getQuizPrizeCall Failure = "+t.getLocalizedMessage());
                    QuizzeSnackBar.showSnackBar(QuizResultScreen.this,binding.getRoot(),getResources().getString(R.string.some_error_occurred),getResources().getColor(R.color.error));
                    startActivity(new Intent(QuizResultScreen.this,MainActivity.class));
                    finish();
                }
            });
        }
        else
        {
            showNoInternetBottomSheet();
        }


    }
    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(QuizResultScreen.this);
        View view = LayoutInflater.from(QuizResultScreen.this).inflate(R.layout.error_occurred_bottom_sheet,findViewById(R.id.errorOccurredBottomSheetLayout),false);
        noInternetBottomSheet.setContentView(view);

        Button contactSupportBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = noInternetBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = noInternetBottomSheet.findViewById(R.id.bottomSheetTitle);
        noInternetBottomSheet.setCancelable(false);
        TextView bottomSheetSubText = noInternetBottomSheet.findViewById(R.id.bottomSheetSubText);
        contactSupportBtn.setVisibility(View.GONE);

        tryAgainBtn.setText(getResources().getString(R.string.try_again));

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckInternetConnection.isInternetConnected(QuizResultScreen.this))
                {
                    noInternetBottomSheet.cancel();
                    getQuizPrize();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(QuizResultScreen.this,view,getResources().getString(R.string.no_internet),getResources().getColor(R.color.error));
                }
            }
        });

        bottomSheetTitle.setText(getResources().getString(R.string.no_internet));
        bottomSheetSubText.setText(getResources().getString(R.string.no_internet_sub_text));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(QuizResultScreen.this,R.drawable.no_conection_illustration));

        if(!QuizResultScreen.this.isFinishing())
        {
            noInternetBottomSheet.show();
        }

    }

}