package com.ElyStudio.leGaou.activities;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
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.LinearLayout;
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.WithdrawMethodAdapter;
import com.ElyStudio.leGaou.databinding.ActivityWalletScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.GetWalletData;
import com.ElyStudio.leGaou.models.WithdrawMethods;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.AppCompat;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.OnWithdrawMethodSelect;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;

import java.util.List;

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

public class WalletScreen extends AppCompat implements OnWithdrawMethodSelect {

    ActivityWalletScreenBinding binding;
    String selectedWithdrawMethod,withdrawMethodIdName,withdrawMethodIcon;
    BottomSheetDialog withdrawBottomSheet;
    int userCoins,minimumWithdrawLimit;
    int conversionRate;
    
    BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet;

    public static final String TAG = "WALLET_SCREEN";

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

        binding.withdrawBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(selectedWithdrawMethod != null && !selectedWithdrawMethod.trim().equals(""))
                {
                    if(userCoins >= minimumWithdrawLimit)
                    {
                        showWithdrawBottomSheet();
                    }
                    else
                    {
                        QuizzeSnackBar.showSnackBar(WalletScreen.this,binding.getRoot(),getResources().getString(R.string.not_enough_coins),getResources().getColor(R.color.error));
                    }
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(WalletScreen.this,binding.getRoot(),getResources().getString(R.string.empty_withdraw_method_warning),getResources().getColor(R.color.error));
                }
            }
        });

    }

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

    private void getWalletData(){

        if(CheckInternetConnection.isInternetConnected(WalletScreen.this))
        {
            Call<GetWalletData> getWalletDataCall = ApiController.getInstance().getApi().getWalletData(FirebaseAuth.getInstance().getUid());

            getWalletDataCall.enqueue(new Callback<GetWalletData>() {
                @Override
                public void onResponse(Call<GetWalletData> call, Response<GetWalletData> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        binding.userCoins.setText(String.valueOf(response.body().getCoins()));
                        userCoins = response.body().getCoins();
                        conversionRate = response.body().getConversionRate();
                        minimumWithdrawLimit = response.body().getMinimumWithdrawLimit();
                        float conversion = (float)response.body().getCoins() / response.body().getConversionRate();
                        binding.coinConversion.setText(conversion+getResources().getString(R.string.default_currency_sign));
                        int maxWithdrawTime = response.body().getMaximumWithdrawTime();
                        binding.withdrawRules.setText(String.format(getResources().getString(R.string.withdraw_rules),maxWithdrawTime));
                        binding.minimumWithdrawLimit.setText(String.format(getResources().getString(R.string.minimum_withdraw_limit),response.body().getMinimumWithdrawLimit()));
                        if(response.body().getWithdrawMethodsList() != null)
                        {
                            setWithdrawMethodRecyclerView(response.body().getWithdrawMethodsList());
                        }
                    }
                    else
                    {
                        showErrorOccurredBottomSheet();
                    }
                }

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

    }
    public void setWithdrawMethodRecyclerView(List<WithdrawMethods> withdrawMethodsList){
        WithdrawMethodAdapter adapter = new WithdrawMethodAdapter(withdrawMethodsList,WalletScreen.this,this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(WalletScreen.this,LinearLayoutManager.HORIZONTAL,false);
        binding.withdrawMethodsRecyclerView.setLayoutManager(layoutManager);
        binding.withdrawMethodsRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onMethodSelected(String name, String idName, String icon) {
        selectedWithdrawMethod = name;
        withdrawMethodIdName = idName;
        withdrawMethodIcon = icon;
    }

    public void showWithdrawBottomSheet(){

        withdrawBottomSheet = new BottomSheetDialog(WalletScreen.this);
        View view = LayoutInflater.from(WalletScreen.this).inflate(R.layout.withdraw_bottom_sheet,findViewById(R.id.withdrawBottomSheetLayout),false);
        withdrawBottomSheet.setContentView(view);

        EditText withdrawMethodEdittext = withdrawBottomSheet.findViewById(R.id.withdrawMethodEditText);
        EditText coinsEditText = withdrawBottomSheet.findViewById(R.id.coinsEditText);
        LinearLayout withdrawInputLayout = withdrawBottomSheet.findViewById(R.id.withdrawInputLayout);
        LinearLayout successfulLayout = withdrawBottomSheet.findViewById(R.id.successfulLayout);
        Button withdrawCoinsBtn = withdrawBottomSheet.findViewById(R.id.withdrawCoinBtn);
        Button thanksBtn = withdrawBottomSheet.findViewById(R.id.thanksBtn);
        withdrawMethodEdittext.setHint(withdrawMethodIdName);

        withdrawCoinsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int coinsInput = Integer.parseInt(coinsEditText.getText().toString().trim());
                String methodId = withdrawMethodEdittext.getText().toString().trim();
                if(!coinsEditText.getText().toString().isEmpty() && !methodId.isEmpty())
                {
                    //Checking users coins with entered coins
                    if(coinsInput <= userCoins)
                    {
                        //Checking entered coins with minimum withdraw limit
                        if(coinsInput >= minimumWithdrawLimit)
                        {
                            float amount = (float) coinsInput / conversionRate;
                            Call<ApiResponse> createWithdrawRequestCall = ApiController.getInstance().getApi().createWithdrawRequest(FirebaseAuth.getInstance().getUid(),
                                    selectedWithdrawMethod,methodId,withdrawMethodIcon,coinsInput,amount,String.format(getResources().getString(R.string.withdraw_activity),selectedWithdrawMethod));

                            createWithdrawRequestCall.enqueue(new Callback<ApiResponse>() {
                                @Override
                                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                                    if(response.body().getStatusCode() == 0)
                                    {
                                        withdrawInputLayout.setVisibility(View.GONE);
                                        successfulLayout.setVisibility(View.VISIBLE);
                                    }
                                    else
                                    {
                                        withdrawBottomSheet.cancel();
                                        QuizzeSnackBar.showSnackBar(WalletScreen.this,binding.getRoot(),getResources().getString(R.string.internal_error),getResources().getColor(R.color.error));
                                    }
                                }

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

                                }
                            });
                        }
                        else
                        {
                            QuizzeSnackBar.showSnackBar(WalletScreen.this,view,getResources().getString(R.string.withdraw_limit_warning),getResources().getColor(R.color.error));
                        }

                    }
                    else
                    {
                        QuizzeSnackBar.showSnackBar(WalletScreen.this,view,getResources().getString(R.string.not_enough_coins),getResources().getColor(R.color.error));
                    }

                }
                else if(methodId.isEmpty())
                {
                    QuizzeSnackBar.showSnackBar(WalletScreen.this,view,String.format(getResources().getString(R.string.withdraw_id_warning),withdrawMethodIdName),getResources().getColor(R.color.error));
                }
                else if(coinsEditText.getText().toString().trim().isEmpty())
                {
                    QuizzeSnackBar.showSnackBar(WalletScreen.this,view,getResources().getString(R.string.empty_coins_warning),getResources().getColor(R.color.error));
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(WalletScreen.this,view,getResources().getString(R.string.empty_withdraw_input_warning),getResources().getColor(R.color.error));
                }
            }
        });

        thanksBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                withdrawBottomSheet.cancel();
                getWalletData();
            }
        });

        if(!WalletScreen.this.isFinishing())
        {
            withdrawBottomSheet.show();
        }

    }
    public void showNoInternetBottomSheet(){

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

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

    }

    public void showErrorOccurredBottomSheet(){

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

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

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