package com.ElyStudio.leGaou.fragment;

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

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

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.LeaderboardAdapter;
import com.ElyStudio.leGaou.databinding.FragmentLeaderboardBinding;
import com.ElyStudio.leGaou.models.GetLeaderboardData;
import com.ElyStudio.leGaou.models.Leaderboard;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
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 LeaderboardFragment extends Fragment {

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

    FragmentLeaderboardBinding binding;
    Context contextFragment;
    BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet;
    public static final String TAG = "LEADERBOARD_SCREEN";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        binding = FragmentLeaderboardBinding.inflate(inflater,container,false);
        return binding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        getLeaderboardData();
    }

    @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;
    }

    private void getLeaderboardData(){

        if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
        {
            Call<GetLeaderboardData> getLeaderboardDataCall = ApiController.getInstance().getApi().getLeaderboardData();

            getLeaderboardDataCall.enqueue(new Callback<GetLeaderboardData>() {
                @Override
                public void onResponse(Call<GetLeaderboardData> call, Response<GetLeaderboardData> response) {
                    if(response.body().getStatusCode() ==  0)
                    {
                        if(response.body().getTopRankers() != null)
                        {
                            setTopRankData(response.body().getTopRankers());
                        }
                        if(response.body().getLeaderboardList() != null)
                        {
                            setLeaderboardRecyclerview(response.body().getLeaderboardList());
                        }
                    }
                }

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

    }

    private void setTopRankData(List<Leaderboard> topRankerList){

        if(topRankerList.size()>2)
        {
            Log.d(TAG,"TOP RANK SIZE = "+topRankerList.size());
            //First Position Data
            if(!topRankerList.get(0).getAvatar().trim().equals(""))
            {
                Picasso.get().load(Constants.ADMIN_PANEL_URL +topRankerList.get(0).getAvatar()).into(binding.firstRankAvatar);
            }
            binding.firstRankName.setText(topRankerList.get(0).getName());
            binding.firstRankCoins.setText(String.valueOf(topRankerList.get(0).getCoins()));

            //Second Position Data
            if(!topRankerList.get(1).getAvatar().trim().equals(""))
            {
                Picasso.get().load(Constants.ADMIN_PANEL_URL+topRankerList.get(1).getAvatar()).into(binding.secondRankAvatar);
            }
            binding.secondRankCoins.setText(topRankerList.get(1).getName());
            binding.secondRankCoins.setText(String.valueOf(topRankerList.get(1).getCoins()));

            //Third Position Data
            if(!topRankerList.get(2).getAvatar().trim().equals(""))
            {
                Picasso.get().load(Constants.ADMIN_PANEL_URL+topRankerList.get(2).getAvatar()).into(binding.thirdRankAvatar);
            }
            binding.thirdRankName.setText(topRankerList.get(2).getName());
            binding.thirdRankCoins.setText(String.valueOf(topRankerList.get(2).getCoins()));
        }
        else
        {

            binding.crownIcon.setVisibility(View.GONE);

            //First Rank
            binding.firstRankAvatarCard.setVisibility(View.GONE);
            binding.firstRankName.setVisibility(View.GONE);
            binding.firstRankCoins.setVisibility(View.GONE);
            binding.firstRankLayout.setVisibility(View.GONE);

            //Second Rank
            binding.secondRankAvatarCard.setVisibility(View.GONE);
            binding.secondRankName.setVisibility(View.GONE);
            binding.secondRankCoins.setVisibility(View.GONE);
            binding.secondRankLayout.setVisibility(View.GONE);

            //Third Rank
            binding.thirdRankAvatarCard.setVisibility(View.GONE);
            binding.thirdRankName.setVisibility(View.GONE);
            binding.thirdRankCoins.setVisibility(View.GONE);
            binding.thirdRankLayout.setVisibility(View.GONE);
        }



    }

    private void setLeaderboardRecyclerview(List<Leaderboard> leaderboardList){
        LeaderboardAdapter adapter = new LeaderboardAdapter(leaderboardList);
        binding.leaderboardRecyclerview.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        binding.leaderboardRecyclerview.setAdapter(adapter);
    }

    public void showNoInternetBottomSheet(){

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

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
                {
                    getLeaderboardData();
                    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();
                getLeaderboardData();
            }
        });

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


}