package com.ElyStudio.leGaou.activities;

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

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
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.BuildConfig;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.adapter.InviteeAdapter;
import com.ElyStudio.leGaou.databinding.ActivityInviteEarnScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.InviteEarnData;
import com.ElyStudio.leGaou.models.Invitee;
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 java.util.List;

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

public class InviteEarnScreen extends AppCompat {

    ActivityInviteEarnScreenBinding binding;
    String userInviteCode;
    String invitedBy;
    int adEnabled;
    String rewardedAdId;

    public static final String TAG = "INVITE_EARN_SCREEN";
    private RewardedAd mRewardedAd;
    int inviteSenderReward;
    BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet;

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

        binding.copyInviteCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inviteCodeLabel = getResources().getString(R.string.app_name)+' '+getResources().getString(R.string.your_invite_code);
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText(inviteCodeLabel, userInviteCode);
                clipboard.setPrimaryClip(clip);

                QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getInviteBonusBtn,getResources().getString(R.string.invite_code_copied),getResources().getColor(R.color.success));

            }
        });

        binding.getInviteBonusBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputInviteCode = binding.inviteCodeEdittext.getText().toString().trim();
                if(inputInviteCode.equals(""))
                {
                    QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.enter_invite_code),getResources().getColor(R.color.error));
                }
                else if(inputInviteCode.length() > 4)
                {
                    QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.invalid_invite_code),getResources().getColor(R.color.error));
                }
                else
                {
                    getInviteBonus(inputInviteCode);
                }
            }
        });

        binding.inviteNowBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String inviteMessage = String.format(getResources().getString(R.string.app_invitation_description),getResources().getString(R.string.app_name),userInviteCode,inviteSenderReward)+'\n';
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name));
                    String shareMessage = inviteMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
                    shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
                    startActivity(Intent.createChooser(shareIntent, "choose one"));
                } catch(Exception e) {
                    Log.d(TAG,"App Sharing Exception = "+e.getLocalizedMessage());
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        setInviteEarnData();
    }

    private void setInviteEarnData(){

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


        if(invitedBy != null)
        {
            binding.inviteCodeEdittext.setVisibility(View.GONE);
            binding.getInviteBonusBtn.setVisibility(View.GONE);
            binding.haveAnyInviteCode.setVisibility(View.GONE);
        }

        userInviteCode = FirebaseAuth.getInstance().getUid().substring(0,4);

        if(CheckInternetConnection.isInternetConnected(InviteEarnScreen.this))
        {
            Call<InviteEarnData> getInviteEarnData = ApiController.getInstance().getApi().getInviteEarnData(userInviteCode);

            getInviteEarnData.enqueue(new Callback<InviteEarnData>() {
                @Override
                public void onResponse(Call<InviteEarnData> call, Response<InviteEarnData> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        String inviteEarnSubtext = String.format(getResources().getString(R.string.invite_earn_instructions),getResources().getString(R.string.app_name),response.body().getInviteSenderReward(),response.body().getInviteReceiverReward());
                        binding.subText.setText(inviteEarnSubtext);
                        binding.userInviteCode.setText(userInviteCode);
                        inviteSenderReward = response.body().getInviteSenderReward();
                        if(response.body().getInviteeList() != null)
                        {
                            setInviteesRecyclerView(response.body().getInviteeList(),InviteEarnScreen.this,response.body().getInviteSenderReward());
                        }

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

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

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

                    }
                    else
                    {
                        showErrorOccurredBottomSheet();
                    }
                }

                @Override
                public void onFailure(Call<InviteEarnData> call, Throwable t) {
                    Log.d(TAG,"getInviteEarnData Failure = "+t.getLocalizedMessage());
                    showErrorOccurredBottomSheet();
                }
            });
        }
        else
        {
            showNoInternetBottomSheet();
        }


    }

    private void getInviteBonus(String inviteCode){

        binding.getInviteBonusBtn.setVisibility(View.GONE);
        binding.inviteCodeEdittext.setVisibility(View.GONE);
        binding.inviteProgressBar.setVisibility(View.VISIBLE);

        if(inviteCode.equals(FirebaseAuth.getInstance().getUid().substring(0,4)))
        {
            binding.getInviteBonusBtn.setVisibility(View.VISIBLE);
            binding.inviteCodeEdittext.setVisibility(View.VISIBLE);
            binding.inviteProgressBar.setVisibility(View.GONE);
            QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.you_cant_entry_your_code),getResources().getColor(R.color.error));
        }
        else
        {

            Call<ApiResponse> getInviteBonus = ApiController.getInstance().getApi().getInviteBonus(FirebaseAuth.getInstance().getUid(),inviteCode,getResources().getString(R.string.invite_earn_sender_activity),getResources().getString(R.string.invitee_activity));

            getInviteBonus.enqueue(new Callback<ApiResponse>() {
                @Override
                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        if(mRewardedAd != null)
                        {
                            mRewardedAd.show(InviteEarnScreen.this, new OnUserEarnedRewardListener() {
                                @Override
                                public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                                    updateInviteUi();
                                }
                            });

                        }
                        else
                        {
                            updateInviteUi();
                        }

                    }
                    else if (response.body().getStatusCode() == 1)
                    {
                        binding.getInviteBonusBtn.setVisibility(View.VISIBLE);
                        binding.inviteCodeEdittext.setVisibility(View.VISIBLE);
                        binding.inviteProgressBar.setVisibility(View.GONE);
                        QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.invalid_invite_code),getResources().getColor(R.color.error));
                    }
                    else
                    {
                        binding.getInviteBonusBtn.setVisibility(View.VISIBLE);
                        binding.inviteCodeEdittext.setVisibility(View.VISIBLE);
                        binding.inviteProgressBar.setVisibility(View.GONE);
                        QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.internal_error),getResources().getColor(R.color.error));
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse> call, Throwable t) {
                    binding.getInviteBonusBtn.setVisibility(View.VISIBLE);
                    binding.inviteCodeEdittext.setVisibility(View.VISIBLE);
                    binding.inviteProgressBar.setVisibility(View.GONE);
                    Log.d(TAG,"getInviteBonus failure = "+t.getLocalizedMessage());
                    QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.some_error_occurred),getResources().getColor(R.color.error));
                }
            });

        }

    }

    public void updateInviteUi(){
        binding.inviteCodeEdittext.setVisibility(View.GONE);
        binding.getInviteBonusBtn.setVisibility(View.GONE);
        binding.haveAnyInviteCode.setVisibility(View.GONE);
        binding.inviteProgressBar.setVisibility(View.GONE);
        QuizzeSnackBar.showSnackBar(InviteEarnScreen.this,binding.getRoot(),getResources().getString(R.string.bonus_claimed),getResources().getColor(R.color.success));
    }

    public void setInviteesRecyclerView(List<Invitee> inviteeList, Context context,int inviteeReward){
        RecyclerView inviteeRecyclerView = binding.inviteeRecyclerview;

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false);
        InviteeAdapter inviteeAdapter = new InviteeAdapter(context,inviteeList,inviteeReward);

        inviteeRecyclerView.setLayoutManager(layoutManager);
        inviteeRecyclerView.setAdapter(inviteeAdapter);
    }

    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(InviteEarnScreen.this);
        View view = LayoutInflater.from(InviteEarnScreen.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(InviteEarnScreen.this))
                {
                    noInternetBottomSheet.cancel();
                    setInviteEarnData();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(InviteEarnScreen.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(InviteEarnScreen.this,R.drawable.no_conection_illustration));

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

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(InviteEarnScreen.this);
        View view = LayoutInflater.from(InviteEarnScreen.this).inflate(R.layout.error_occurred_bottom_sheet,findViewById(R.id.errorOccurredBottomSheetLayout),false);
        errorOccurredBottomSheet.setContentView(view);
        errorOccurredBottomSheet.setCancelable(false);
        Button contactSupportBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = errorOccurredBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = errorOccurredBottomSheet.findViewById(R.id.bottomSheetTitle);
        TextView bottomSheetSubText = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSubText);

        bottomSheetTitle.setText(getResources().getString(R.string.some_error_occurred));
        bottomSheetSubText.setText(getResources().getString(R.string.error_subtext));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(InviteEarnScreen.this,R.drawable.error_illustration));
        contactSupportBtn.setText(getResources().getString(R.string.contact_support));
        tryAgainBtn.setText(getResources().getString(R.string.try_again));

        contactSupportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(InviteEarnScreen.this, SupportScreen.class));
            }
        });

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                errorOccurredBottomSheet.cancel();
                setInviteEarnData();
            }
        });

        if(!InviteEarnScreen.this.isFinishing())
        {
            errorOccurredBottomSheet.show();
        }
    }

}