package com.ElyStudio.leGaou.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.CompositePageTransformer;
import androidx.viewpager2.widget.MarginPageTransformer;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.activities.SupportScreen;
import com.ElyStudio.leGaou.adapter.GamesAdapter;
import com.ElyStudio.leGaou.adapter.TrendingGamesAdapter;
import com.ElyStudio.leGaou.databinding.FragmentGamesBinding;
import com.ElyStudio.leGaou.models.Games;
import com.ElyStudio.leGaou.models.GetGameScreenData;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.GridViewSpacing;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;

import java.util.List;

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

public class GamesFragment extends Fragment {


    public GamesFragment() {
        // Required empty public constructor
    }

    FragmentGamesBinding binding;
    Context contextFragment;
    public static final String TAG = "GAMES_FRAGMENT";
    BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet;

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

        getGamesScreenData();

        return binding.getRoot();
    }

    private void getGamesScreenData(){

        if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
        {

            Call<GetGameScreenData> getGameScreenDataCall = ApiController.getInstance().getApi().getGameScreenData();

            getGameScreenDataCall.enqueue(new Callback<GetGameScreenData>() {
                @Override
                public void onResponse(Call<GetGameScreenData> call, Response<GetGameScreenData> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        int adEnabled = response.body().getAdEnabled();
                        String interstitialAdId = response.body().getInterstitialAdId();
                        if(response.body().getTrendingGameList() != null)
                        {
                            setTrendingGamesViewPager(response.body().getTrendingGameList(),getContextNullSafety(),adEnabled,interstitialAdId);
                        }
                        if(response.body().getGamesList() != null )
                        {
                            setGamesRecyclerView(response.body().getGamesList(),getContextNullSafety(),adEnabled,interstitialAdId);
                        }
                    }
                    else
                    {
                        QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getResources().getString(R.string.some_error_occurred),getResources().getColor(R.color.error));
                        showErrorOccurredBottomSheet();
                    }
                }

                @Override
                public void onFailure(Call<GetGameScreenData> call, Throwable t) {
                    Log.d(TAG,"getGameScreenDataCall Failure = "+t.getLocalizedMessage());
                    showErrorOccurredBottomSheet();

                }
            });
        }
        else
        {
            showNoInternetBottomSheet();
        }

    }

    private void setGamesRecyclerView(List<Games> gamesList,Context context,int adEnabled,String interstitialAdId){

        RecyclerView gamesRecyclerview = binding.gamesRecyclerView;
        GamesAdapter gamesAdapter = new GamesAdapter(context,getActivityNullSafety(),gamesList,adEnabled,interstitialAdId);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(context,2,RecyclerView.VERTICAL,false);
        gamesRecyclerview.addItemDecoration(new GridViewSpacing(2,40,false));
        gamesRecyclerview.setLayoutManager(layoutManager);
        gamesRecyclerview.setAdapter(gamesAdapter);

    }

    private void setTrendingGamesViewPager(List<Games> gamesList, Context context,int adEnabled, String interstitialAdId){

        ViewPager2 trendingGamesViewPager = binding.trendingGameViewPager;
        trendingGamesViewPager.setClipToPadding(false);
        trendingGamesViewPager.setClipChildren(false);
        trendingGamesViewPager.setOffscreenPageLimit(5);
        TrendingGamesAdapter gamesAdapter = new TrendingGamesAdapter(gamesList,context,getActivityNullSafety(),adEnabled,interstitialAdId);
        trendingGamesViewPager.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);

        CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
        compositePageTransformer.addTransformer(new MarginPageTransformer(40));
        compositePageTransformer.addTransformer(new ViewPager2.PageTransformer() {
            @Override
            public void transformPage(@NonNull View page, float position) {
                float r = 1 - Math.abs(position);
                page.setScaleY(0.85f + r * 0.15f);
            }
        });
        trendingGamesViewPager.setPageTransformer(compositePageTransformer);
        trendingGamesViewPager.setAdapter(gamesAdapter);

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextFragment = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
        if (getContext() != null) return getContext();
        if (getActivity() != null) return getActivity();
        if (contextFragment != null) return contextFragment;
        if (getView() != null && getView().getContext() != null) return getView().getContext();
        if (requireContext() != null) return requireContext();
        if (requireActivity() != null) return requireActivity();
        if (requireView() != null && requireView().getContext() != null)
            return requireView().getContext();

        return null;
    }
    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }
    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().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(getActivityNullSafety().getResources().getString(R.string.try_again));

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

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

        if(!getActivityNullSafety().isFinishing())
        {
            noInternetBottomSheet.show();
        }

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().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(getActivityNullSafety().getResources().getString(R.string.some_error_occurred));
        bottomSheetSubText.setText(getActivityNullSafety().getResources().getString(R.string.error_subtext));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.error_illustration));
        contactSupportBtn.setText(getActivityNullSafety().getResources().getString(R.string.contact_support));
        tryAgainBtn.setText(getActivityNullSafety().getResources().getString(R.string.try_again));

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

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

        if(!getActivityNullSafety().isFinishing())
        {
            errorOccurredBottomSheet.show();
        }
    }


}