package com.ElyStudio.leGaou.activities;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.adapter.AvatarAdapter;
import com.ElyStudio.leGaou.databinding.ActivityAvatarSelectionScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.Avatars;
import com.ElyStudio.leGaou.models.QuizzeAvatars;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.AppCompat;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.OnItemClick;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;

import java.util.List;

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

public class AvatarSelectionScreen extends AppCompat implements OnItemClick {

    ActivityAvatarSelectionScreenBinding binding;
    public static final String TAG = "AVATAR_SELECTION_SCREEN";
    RecyclerView avatarRecyclerView;
    String avatarImage;
    BottomSheetDialog nameInputBottomSheet,errorOccurredBottomSheet,noInternetBottomSheet;

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

        binding.nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(avatarImage != null && !avatarImage.equals(""))
                {
                    showNameInputBottomSheet();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(AvatarSelectionScreen.this,binding.getRoot(),getResources().getString(R.string.select_avatar_warning),getResources().getColor(R.color.warning));
                }
            }
        });

    }

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

    private void getAvatars(){

        if(CheckInternetConnection.isInternetConnected(AvatarSelectionScreen.this))
        {
            Call<QuizzeAvatars> getAvatarsCall = ApiController.getInstance().getApi().getAvatars();

            getAvatarsCall.enqueue(new Callback<QuizzeAvatars>() {
                @Override
                public void onResponse(Call<QuizzeAvatars> call, Response<QuizzeAvatars> response) {
                    assert response.body() != null;
                    if(response.body().getstatusCode() == 0)
                    {
                        if(response.body().avatarsList != null)
                        {
                            setAvatarRecyclerView(response.body().avatarsList);
                        }
                    }
                    else if (response.body().getstatusCode()==1)
                    {
                        QuizzeSnackBar.showSnackBar(AvatarSelectionScreen.this,binding.getRoot(),getResources().getString(R.string.no_avatars_available),getResources().getColor(R.color.error));
                    }
                    else
                    {
                        showErrorOccurredBottomSheet();
                    }
                }

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


    }

    void setAvatarRecyclerView(List<Avatars> avatarsList){
        avatarRecyclerView = binding.avatarsRecyclerview;

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(AvatarSelectionScreen.this,2,RecyclerView.VERTICAL,false);
        AvatarAdapter adapter = new AvatarAdapter(avatarsList,this);

        avatarRecyclerView.setLayoutManager(layoutManager);
        avatarRecyclerView.setAdapter(adapter);

    }

    @Override
    public void onClick(String value) {
        avatarImage = value;
    }

    private void showNameInputBottomSheet(){

        nameInputBottomSheet = new BottomSheetDialog(AvatarSelectionScreen.this);
        View view = LayoutInflater.from(AvatarSelectionScreen.this).inflate(R.layout.name_input_bottomsheet,findViewById(R.id.nameInputBottomSheet));
        nameInputBottomSheet.setContentView(view);

        EditText nameInput = view.findViewById(R.id.userNameInput);
        Button completeButton = view.findViewById(R.id.completeButton);

        completeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameInput.getText().toString();
                if(name.equals(""))
                {
                    QuizzeSnackBar.showSnackBar(AvatarSelectionScreen.this,view,getResources().getString(R.string.enter_name_warning),getResources().getColor(R.color.warning));
                }
                else
                {
                    updateSignIn(name,avatarImage);
                }
            }
        });

        nameInputBottomSheet.show();

    }

    void updateSignIn(String name, String avatar){

        Call<ApiResponse> updateSignInCall = ApiController.getInstance().getApi().updateSignIn(FirebaseAuth.getInstance().getUid(), name,avatar);

        updateSignInCall.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {

                if(response.body().getStatusCode() == 0)
                {
                    nameInputBottomSheet.cancel();
                    startActivity(new Intent(AvatarSelectionScreen.this,MainActivity.class));
                    finish();
                }
                else
                {
                    nameInputBottomSheet.cancel();
                    QuizzeSnackBar.showSnackBar(AvatarSelectionScreen.this,binding.getRoot(),getResources().getString(R.string.internal_error),getResources().getColor(R.color.error));
                }


            }

            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                nameInputBottomSheet.cancel();
                QuizzeSnackBar.showSnackBar(AvatarSelectionScreen.this,binding.getRoot(),getResources().getString(R.string.some_error),getResources().getColor(R.color.error));
                Log.d(TAG,"updateSignInCall Failure = "+t.getLocalizedMessage());
            }
        });

    }

    public void showNoInternetBottomSheet(){

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

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

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(AvatarSelectionScreen.this);
        View view = LayoutInflater.from(AvatarSelectionScreen.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(AvatarSelectionScreen.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(AvatarSelectionScreen.this, SupportScreen.class));
            }
        });

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

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