package com.ElyStudio.leGaou.activities;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

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.android.material.card.MaterialCardView;
import com.google.firebase.auth.FirebaseAuth;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.databinding.ActivityUserProfileScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.UserData;
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 com.squareup.picasso.Picasso;

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

public class UserProfileScreen extends AppCompat {

    ActivityUserProfileScreenBinding binding;
    BottomSheetDialog updateBottomSheet,updateNameBottomSheet,noInternetBottomSheet,errorOccurredBottomSheet;
    
    public static final String TAG = "USER_PROFILE SCREEN";
    String userName;
    

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

        binding.viewQuizHistoryCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UserProfileScreen.this,QuizHistoryScreen.class));
            }
        });

        binding.updateDetailsCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUpdateBottomSheet();
            }
        });

    }

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

    private void getUserData(){

        if(CheckInternetConnection.isInternetConnected(UserProfileScreen.this))
        {
            Call<UserData> getUserDataCall = ApiController.getInstance().getApi().getUserData(FirebaseAuth.getInstance().getUid());

            getUserDataCall.enqueue(new Callback<UserData>() {
                @Override
                public void onResponse(Call<UserData> call, Response<UserData> response) {
                    assert response.body() != null;
                    if(response.body().getStatusCode()==0)
                    {
                        UserData user = response.body();
                        userName = user.getName();
                        binding.profileUserName.setText(user.getName());
                        binding.profileUserEmail.setText(user.getEmail());
                        binding.profileUserCoins.setText(String.valueOf(user.getCoins()));
                        binding.profileUserTotalCoins.setText(String.valueOf(user.getTotalCoins()));
                        binding.profileUserLevel.setText(user.getUserLevel());
                        if(!user.getUserLevelIcon().trim().isEmpty())
                        {
                            Picasso.get().load(Constants.ADMIN_PANEL_URL+user.getUserLevelIcon()).into(binding.profileUserLevelIcon);
                        }
                        else
                        {
                            binding.profileUserLevelIcon.setImageDrawable(ContextCompat.getDrawable(UserProfileScreen.this,R.drawable.image_placeholder));
                        }

                        if(!user.getAvatar().trim().isEmpty())
                        {
                            Picasso.get().load(Constants.ADMIN_PANEL_URL+user.getAvatar()).into(binding.userProfileAvatar);
                        }
                        else
                        {
                            binding.userProfileAvatar.setImageDrawable(ContextCompat.getDrawable(UserProfileScreen.this,R.drawable.image_placeholder));
                        }
                    }
                    else
                    {
                        showErrorOccurredBottomSheet();
                    }
                }

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

    }

    public void showUpdateBottomSheet(){

        updateBottomSheet = new BottomSheetDialog(UserProfileScreen.this);
        View view = LayoutInflater.from(UserProfileScreen.this).inflate(R.layout.update_bottomsheet,(ConstraintLayout) findViewById(R.id.updateBottomSheetLayout),false);
        updateBottomSheet.setContentView(view);
        MaterialCardView changeAvatarCard = updateBottomSheet.findViewById(R.id.changeAvatarCard);
        MaterialCardView  updateNameCard = updateBottomSheet.findViewById(R.id.updateNameCard);

        updateNameCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(updateBottomSheet.isShowing())
                {
                    updateBottomSheet.cancel();
                }
                showUpdateNameBottomSheet();
            }
        });

        changeAvatarCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UserProfileScreen.this,UpdateAvatarActivity.class));
            }
        });

        if(!UserProfileScreen.this.isFinishing())
        {
            updateBottomSheet.show();
        }

    }

    private void showUpdateNameBottomSheet(){

        updateNameBottomSheet = new BottomSheetDialog(UserProfileScreen.this);
        View view = LayoutInflater.from(UserProfileScreen.this).inflate(R.layout.update_name_bottomsheet,(ConstraintLayout) findViewById(R.id.updateNameBottomSheetLayout),false);
        updateNameBottomSheet.setContentView(view);

        EditText updateNameEditText = updateNameBottomSheet.findViewById(R.id.updateNameEditText);
        Button updateNameBtn = updateNameBottomSheet.findViewById(R.id.updateNameBtn);
        updateNameEditText.setText(userName);

        updateNameBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(updateNameEditText.getText().toString().equals(userName))
                {
                    if(updateNameBottomSheet.isShowing())
                    {
                        updateNameBottomSheet.cancel();
                    }
                }
                else if(updateNameEditText.getText().toString().trim().isEmpty())
                {
                    QuizzeSnackBar.showSnackBar(UserProfileScreen.this,view,getResources().getString(R.string.update_name_error),getResources().getColor(R.color.error));
                }
                else
                {
                    updateName(updateNameEditText.getText().toString());
                }
            }
        });

        if(!UserProfileScreen.this.isFinishing())
        {
            updateNameBottomSheet.show();
        }


    }

    private void updateName(String name){

        Call<ApiResponse> updateNameCall = ApiController.getInstance().getApi().updateName(FirebaseAuth.getInstance().getUid(), name);
        updateNameCall.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                if(response.body().getStatusCode() == 0)
                {
                    if(updateNameBottomSheet.isShowing())
                    {
                        updateNameBottomSheet.cancel();
                        QuizzeSnackBar.showSnackBar(UserProfileScreen.this,binding.getRoot(),getResources().getString(R.string.name_updated),getResources().getColor(R.color.success));
                        getUserData();
                    }

                }
                else
                {
                    QuizzeSnackBar.showSnackBar(UserProfileScreen.this,binding.getRoot(),getResources().getString(R.string.internal_error),getResources().getColor(R.color.error));
                }

            }

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

    }

    public void showNoInternetBottomSheet(){

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

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

    }

    public void showErrorOccurredBottomSheet(){

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

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

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