package com.ElyStudio.leGaou.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
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.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.card.MaterialCardView;
import com.google.firebase.auth.FirebaseAuth;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.activities.MainActivity;
import com.ElyStudio.leGaou.activities.QuizScreen;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.Quiz;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;
import com.squareup.picasso.Picasso;

import java.util.List;

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

public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.QuizViewHolder> {

    private final Context context;
    private final List<Quiz> quizList;
    private final Activity activity;
    private final View view;
    private final int userCoins;
    private final int watchEarnReward;
    private final int adEnabled;
    private final String nativeAdId;
    private final String interstitialAdId;
    private final String rewardedAdId;

    BottomSheetDialog quizBottomSheet;
    BottomSheetDialog noCoinsBottomSheet;
    private RewardedAd mRewardedAd;
    private InterstitialAd mInterstitialAd;
    public static final String TAG = "QUIZ_ADAPTER";

    LottieAnimationView loadingAnimationAd,quizLoadingAnimation;
    MaterialCardView watchAdBtn;
    Button playButton;

    public QuizAdapter(Context context, List<Quiz> quizList, Activity activity, View view, int userCoins, int watchEarnReward, int adEnabled, String nativeAdId, String interstitialAdId, String rewardedAdId) {
        this.context = context;
        this.quizList = quizList;
        this.activity = activity;
        this.view = view;
        this.userCoins = userCoins;
        this.watchEarnReward = watchEarnReward;
        this.adEnabled = adEnabled;
        this.nativeAdId = nativeAdId;
        this.interstitialAdId = interstitialAdId;
        this.rewardedAdId = rewardedAdId;
    }

    @NonNull
    @Override
    public QuizAdapter.QuizViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new QuizViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.quiz_card_layout,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull QuizAdapter.QuizViewHolder holder, int position) {

        loadInterstitialAd();
        loadRewardedAdvertisement();

        Quiz quiz = quizList.get(position);
        int quizCardColor,quizTitleColor;
        if(quiz.getColorCode() == 1)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_1);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_1);
        }
        else if(quiz.getColorCode() == 2)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_2);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_2);
        }
        else if(quiz.getColorCode() == 3)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_3);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_3);
        }
        else if(quiz.getColorCode() == 4)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_4);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_4);
        }
        else if(quiz.getColorCode() == 5)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_5);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_5);
        }
        else if(quiz.getColorCode() == 6)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_6);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_6);
        }
        else if(quiz.getColorCode() == 7)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_7);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_7);
        }
        else if(quiz.getColorCode() == 8)
        {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_8);
            quizTitleColor = context.getResources().getColor(R.color.quiz_color_text_8);
        }
        else {
            quizCardColor = context.getResources().getColor(R.color.quiz_color_bg_default);
            quizTitleColor = context.getResources().getColor(R.color.primary_text_color);
            holder.quizCard.setCardElevation(2);
        }

        holder.quizCard.setCardBackgroundColor(quizCardColor);
        holder.quizTitle.setText(quiz.getName());
        holder.quizTitle.setTextColor(quizTitleColor);
        if(quiz.getEntryFee() == 0)
        {
            holder.quizEntryFee.setText(context.getResources().getString(R.string.free));
            holder.coinIcon.setVisibility(View.GONE);
        }
        else
        {
            holder.quizEntryFee.setText(String.valueOf(quiz.getEntryFee()));
        }
        if(!quiz.getIcon().trim().isEmpty())
        {
            Picasso.get().load(Constants.ADMIN_PANEL_URL +quiz.getIcon()).into(holder.quizIcon);
        }
        else
        {
            holder.quizIcon.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.image_placeholder));
        }

        holder.quizCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showQuizBottomSheet(quizTitleColor,quiz);
            }
        });


    }

    @Override
    public int getItemCount() {
        return quizList.size();
    }

    public class QuizViewHolder extends RecyclerView.ViewHolder {

        MaterialCardView quizCard;
        TextView quizTitle,quizEntryFee;
        ImageView quizIcon,coinIcon;

        public QuizViewHolder(@NonNull View itemView) {
            super(itemView);

            quizCard = itemView.findViewById(R.id.quizCard);
            quizTitle = itemView.findViewById(R.id.quizTitle);
            quizEntryFee = itemView.findViewById(R.id.quizEntryFee);
            quizIcon = itemView.findViewById(R.id.quizIcon);
            coinIcon = itemView.findViewById(R.id.coinIcon);

        }
    }

    void showQuizBottomSheet(int color,Quiz quiz){
        quizBottomSheet = new BottomSheetDialog(context);
        View bottomSheetView = LayoutInflater.from(context).inflate(R.layout.quiz_bottomsheet_layout,(ConstraintLayout) view.findViewById(R.id.quizBottomSheet),false);
        quizBottomSheet.setContentView(bottomSheetView);
        quizBottomSheet.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                BottomSheetDialog a = (BottomSheetDialog) quizBottomSheet;
                FrameLayout bottomSheet = (FrameLayout) a.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                assert bottomSheet != null;
                BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        TextView quizTitle = quizBottomSheet.findViewById(R.id.bottomSheetQuizTitle);
        ImageView quizIcon = quizBottomSheet.findViewById(R.id.bottomSheetQuizIcon);
        TextView quizRulesTv = quizBottomSheet.findViewById(R.id.bottomSheetQuizRules);
        TextView entryFee = quizBottomSheet.findViewById(R.id.bottomSheetQuizEntryFee);
        ImageView coinIcon = quizBottomSheet.findViewById(R.id.bottomSheetQuizCoinIcon);
        playButton = quizBottomSheet.findViewById(R.id.quizPlayButton);
        quizLoadingAnimation = quizBottomSheet.findViewById(R.id.quizLoadingAnimation);
        String quizRules = String.format(context.getResources().getString(R.string.quiz_rule_one),quiz.getQuestionLimit())+'\n'
                    +String.format(context.getResources().getString(R.string.quiz_rule_two),quiz.getLivesAvailable())+'\n'
                    +context.getResources().getString(R.string.quiz_rule_three)+'\n'
                    +context.getResources().getString(R.string.quiz_rule_four)+'\n'
                    +context.getResources().getString(R.string.quiz_rule_five);
        assert quizTitle != null;
        quizTitle.setTextColor(color);
        quizTitle.setText(quiz.getName());
        quizRulesTv.setText(quizRules);
        if(quiz.getEntryFee() == 0)
        {
            entryFee.setText(context.getResources().getString(R.string.free));
            coinIcon.setVisibility(View.GONE);
        }
        else
        {
            entryFee.setText(String.valueOf(quiz.getEntryFee()));
        }
        if(!quiz.getIcon().trim().isEmpty())
        {
            Picasso.get().load(Constants.ADMIN_PANEL_URL+quiz.getIcon()).into(quizIcon);
        }
        else
        {
            quizIcon.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.image_placeholder));
        }
        playButton.setBackgroundColor(color);

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playQuiz(quiz);
            }
        });

        if(!activity.isFinishing())
        {
            quizBottomSheet.show();
        }

    }

    public void playQuiz(Quiz quiz){

        if(quiz.getEntryFee()<=userCoins) {

            int paid;

            if (quiz.getEntryFee() != 0) {
                paid = 1;
            } else {
                paid = 0;
            }

            Call<ApiResponse> playQuizCall = ApiController.getInstance().getApi().playQuiz(FirebaseAuth.getInstance().getUid(), quiz.getIcon(), quiz.getName() + context.getResources().getString(R.string.entry_fee), quiz.getEntryFee(), paid);

            playQuizCall.enqueue(new Callback<ApiResponse>() {
                @Override
                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                    if (response.body().getStatusCode() == 0) {
                            showInterstitialAd(quiz);
                    } else {
                        QuizzeSnackBar.showSnackBar(context, view, context.getResources().getString(R.string.internal_error), context.getResources().getColor(R.color.error));
                        Log.d(TAG, response.body().getMessage());
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse> call, Throwable t) {
                    QuizzeSnackBar.showSnackBar(context, view, context.getResources().getString(R.string.some_error_occurred), context.getResources().getColor(R.color.error));
                    Log.d(TAG, "playQuizCall Failure = " + t.getLocalizedMessage());
                }
            });

        }
        else
        {
            showNoCoinsBottomSheet();
        }

    }


    public void showNoCoinsBottomSheet(){

        if(quizBottomSheet.isShowing())
        {
            quizBottomSheet.cancel();
        }
        noCoinsBottomSheet = new BottomSheetDialog(context);
        View noCoinsBottomSheetView = LayoutInflater.from(context).inflate(R.layout.no_coins_bottom_sheet,(ConstraintLayout)view.findViewById(R.id.noCoinsBottomSheetLayout),false);
        noCoinsBottomSheet.setContentView(noCoinsBottomSheetView);

        watchAdBtn = noCoinsBottomSheetView.findViewById(R.id.watchCoinsAdBtn);
        TextView noCoinsSubText = noCoinsBottomSheetView.findViewById(R.id.noCoinsSubtext);
        TextView watchAdBtnTitle = noCoinsBottomSheetView.findViewById(R.id.watchCoinsAdBtnTitle);
        loadingAnimationAd = noCoinsBottomSheetView.findViewById(R.id.loadingAnimationAd);
        String noCoinsDesc = context.getString(R.string.watch_ad_sub_text)+" +"+watchEarnReward;
        noCoinsSubText.setText(noCoinsDesc);
        String watchAdTitle = context.getResources().getString(R.string.watch_ad)+" +"+watchEarnReward+' '+context.getResources().getString(R.string.coins);
        watchAdBtnTitle.setText(watchAdTitle);

        watchAdBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingAnimationAd.setVisibility(View.VISIBLE);
                watchAdBtn.setVisibility(View.GONE);
                showRewardedAd();
            }
        });

        if(!activity.isFinishing())
        {
            noCoinsBottomSheet.show();
        }

    }

    public void showRewardedAd(){

        if(adEnabled == 1)
        {
            if(mRewardedAd != null)
            {
                mRewardedAd.show(activity, new OnUserEarnedRewardListener() {
                    @Override
                    public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                        getAdReward();
                        activity.startActivity(new Intent(context, MainActivity.class));
                        activity.finish();
                    }
                });
            }
            else
            {
                if (loadingAnimationAd != null && watchAdBtn != null) {
                    loadingAnimationAd.setVisibility(View.GONE);
                    watchAdBtn.setVisibility(View.VISIBLE);
                    QuizzeSnackBar.showSnackBar(context,view,context.getResources().getString(R.string.no_ads_available),context.getResources().getColor(R.color.error));
                }
            }
        }
        else
        {
            if (loadingAnimationAd != null && watchAdBtn != null) {
                loadingAnimationAd.setVisibility(View.GONE);
                watchAdBtn.setVisibility(View.VISIBLE);
                QuizzeSnackBar.showSnackBar(context,view,context.getResources().getString(R.string.no_ads_available),context.getResources().getColor(R.color.error));
            }
        }

    }

    public void loadRewardedAdvertisement(){

        AdRequest adRequest = new AdRequest.Builder().build();

        RewardedAd.load(context, rewardedAdId, adRequest, new RewardedAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                Log.d(TAG,"Failed to load interstitial ad = "+loadAdError);
                mRewardedAd = null;
            }

            @Override
            public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                super.onAdLoaded(rewardedAd);
                mRewardedAd = rewardedAd;
            }
        });

    }

    public void showInterstitialAd(Quiz quiz){

        if(playButton != null && quizLoadingAnimation !=null)
        {
            playButton.setVisibility(View.GONE);
            quizLoadingAnimation.setVisibility(View.VISIBLE);
        }

        if(adEnabled == 1)
        {
            if(mInterstitialAd!= null)
            {
                mInterstitialAd.show(activity);

                mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        super.onAdDismissedFullScreenContent();
                        starQuiz(quiz);
                    }
                });
            }
            else
            {
                starQuiz(quiz);
            }

        }
        else
        {
            starQuiz(quiz);
            mInterstitialAd = null;
        }


    }

    public void getAdReward(){
        if (noCoinsBottomSheet.isShowing())
        {
            noCoinsBottomSheet.cancel();
        }

        Call<ApiResponse> getAdRewardCall = ApiController.getInstance().getApi().getAdCoins(FirebaseAuth.getInstance().getUid(), watchEarnReward,context.getResources().getString(R.string.watch_reward),0);

        getAdRewardCall.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                if(response.body().statusCode==0)
                {
                    QuizzeSnackBar.showSnackBar(context,view,"User Earned Reward",context.getResources().getColor(R.color.success));
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(context,view,context.getResources().getString(R.string.internal_error),context.getResources().getColor(R.color.error));
                }
            }

            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                Log.d(TAG,"getAdRewardCall Failure = "+t.getLocalizedMessage());
                QuizzeSnackBar.showSnackBar(context,view,context.getResources().getString(R.string.some_error_occurred),context.getResources().getColor(R.color.error));
            }
        });

    }

    public void starQuiz(Quiz quiz){
        if(quizBottomSheet.isShowing())
        {
            quizBottomSheet.cancel();
        }
        Intent intent = new Intent(context, QuizScreen.class);

        intent.putExtra(Constants.quizId,quiz.getId());
        intent.putExtra(Constants.quizName,quiz.getName());
        intent.putExtra(Constants.quizIcon,quiz.getIcon());
        intent.putExtra(Constants.quizEntryFee,quiz.getEntryFee());
        intent.putExtra(Constants.quizColorCode,quiz.getColorCode());

        intent.putExtra(Constants.quizDifficultyEasy,quiz.getEasy());
        intent.putExtra(Constants.quizDifficultyMedium,quiz.getMedium());
        intent.putExtra(Constants.quizDifficultyHard,quiz.getHard());

        intent.putExtra(Constants.quizQuestionLimit,quiz.getQuestionLimit());
        intent.putExtra(Constants.quizLivesAvailable, quiz.getLivesAvailable());
        intent.putExtra(Constants.quizTimeAvailable, quiz.getTime());
        intent.putExtra(Constants.quizPrizePerQuestion,quiz.getPrizePerQuestion());

        intent.putExtra(Constants.adEnabled,adEnabled);
        intent.putExtra(Constants.nativeAdId,nativeAdId);
        intent.putExtra(Constants.interstitialAdId,interstitialAdId);
        intent.putExtra(Constants.rewardedAdId,rewardedAdId);

        context.startActivity(intent);
    }

    public void loadInterstitialAd(){

        AdRequest adRequest = new AdRequest.Builder().build();

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

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