package ch.pizzalemon.android.activity;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.adapter.recycler.ProductCheckboxOptionsRecyclerAdapter;
import ch.pizzalemon.android.adapter.recycler.ProductRadioOptionsRecyclerAdapter;
import ch.pizzalemon.android.api.ApiConstants;
import ch.pizzalemon.android.api.ApiEndPoints;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseObject;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.ImageLoadHelper;
import ch.pizzalemon.android.helper.PriceHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.helper.TextHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.AddProductToBasketResponseModel;
import ch.pizzalemon.android.model.CampaignModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import ch.pizzalemon.android.model.menu.MenuProductModel;
import ch.pizzalemon.android.model.menu.MenuProductOptionModel;
import ch.pizzalemon.android.model.menu.MenuProductOptionValueModel;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductDetailsActivity extends BaseActivity {

    @BindView(R.id.closeImageView) ImageView closeImageView;
    @BindView(R.id.backIcon) ImageView backIcon;
    @BindView(R.id.productImageView) ImageView productImageView;
    @BindView(R.id.productNameTextView) TextView productNameTextView;
    @BindView(R.id.productPriceTextView) TextView productPriceTextView;
    @BindView(R.id.productDescriptionTextView) TextView productDescriptionTextView;
    @BindView(R.id.wunschpizzaAlertTextView) TextView wunschpizzaAlertTextView;
    @BindView(R.id.addToCartButton) Button addToCartButton;
    @BindView(R.id.recycler1HeaderTextView) TextView recycler1HeaderTextView;
    @BindView(R.id.recyclerView1) RecyclerView recyclerView1;
    @BindView(R.id.recycler2HeaderTextView) TextView recycler2HeaderTextView;
    @BindView(R.id.recyclerView2) RecyclerView recyclerView2;
    @BindView(R.id.increaseProductCountImageView) ImageView increaseProductCountImageView;
    @BindView(R.id.deccreaseProductCountImageView) ImageView deccreaseProductCountImageView;
    @BindView(R.id.productCountTextView) TextView productCountTextView;

    @BindString(R.string.no_options_selected_part) String noOptionsSelectedText;

    private int productCount = 1;

    private MenuProductModel menuProductModel;
    private CampaignModel campaignModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);
        ButterKnife.bind(this);
        getDataFromIntent();
        initViews();
    }

    @OnClick({R.id.closeImageView,
            R.id.backIcon,
            R.id.increaseProductCountImageView,
            R.id.deccreaseProductCountImageView,
            R.id.addToCartButton})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.closeImageView:
            case R.id.backIcon:
                finish();
                break;
            case R.id.increaseProductCountImageView:
                productCount++;
                productCountTextView.setText(String.valueOf(productCount));
                productPriceTextView.setText(
                        PriceHelper.calculatePriceAfterCountChanged(
                                productPriceTextView.getText().toString(), productCount - 1, productCount));
                break;
            case R.id.deccreaseProductCountImageView:
                if(productCount == 1)
                    break;
                productCount--;
                productCountTextView.setText(String.valueOf(productCount));
                productPriceTextView.setText(
                        PriceHelper.calculatePriceAfterCountChanged(
                                productPriceTextView.getText().toString(), productCount + 1, productCount));
                break;
            case R.id.addToCartButton:
                if(checkFields()){
                    if(SessionHelper.isCustomerLoggedIn()){
                        addProductToCart();
                    }
                    else {
                        DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_shopping);
                    }
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
                menuProductOptionValueModel.setSelected(false);
            }
        }

        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
                if(menuProductOptionValueModel.getPrice().equals("0") || menuProductOptionValueModel.getPrice().equals("0.00")){
                    /*
                    //checkbox
                    if(!(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                            menuProductOptionModel.getType().toLowerCase().equals("select"))){
                        menuProductOptionValueModel.setSelected(true);
                    }

                    //radio
                    else if(!isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList())){
                        menuProductOptionValueModel.setSelected(true);
                    }
                    */
                    boolean isRadio = menuProductOptionModel.getType().toLowerCase().equals("radio") || menuProductOptionModel.getType().toLowerCase().equals("select");
                    boolean isAnyOptionValueSelected = isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList());
                    if(isRadio && !isAnyOptionValueSelected){
                        menuProductOptionValueModel.setSelected(true);
                    }

                }
            }
        }
    }

    private void getDataFromIntent(){
        menuProductModel = (MenuProductModel) getIntent().getSerializableExtra("menuProductModel");
    }

    private void initViews(){
        setFields();
        initRecyclerViews();
    }

    public void setMenuProductModel(MenuProductModel menuProductModel){
        this.menuProductModel = menuProductModel;
    }

    private void initRecyclerViews(){
        fixRadioAndCheckbox();
        for(int i = 0; i < menuProductModel.getProductOptionList().size(); i++){
            MenuProductOptionModel menuProductOptionModel = menuProductModel.getProductOptionList().get(i);
            setSelectedPriceShowingOptions(menuProductOptionModel);
            switch (i){
                case 0:
                    initRecyclerView(
                            recycler1HeaderTextView,
                            recyclerView1,
                            menuProductOptionModel);
                    break;
                case 1:
                    initRecyclerView(
                            recycler2HeaderTextView,
                            recyclerView2,
                            menuProductOptionModel);
                    break;
            }
        }
    }

    private void initRecyclerView(TextView headerTextView,
                                  RecyclerView recyclerView,
                                  final MenuProductOptionModel menuProductOptionModel){
        headerTextView.setText(menuProductOptionModel.getName());
        recyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(BaseActivity.currentActivity, 1);
        recyclerView.setLayoutManager(gridLayoutManager);


        if(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                menuProductOptionModel.getType().toLowerCase().equals("select")){

            final ProductRadioOptionsRecyclerAdapter productRadioOptionsRecyclerAdapter =
                    new ProductRadioOptionsRecyclerAdapter(menuProductOptionModel.getOptionValueModelList());
            productRadioOptionsRecyclerAdapter.setRecyclerItemClickListener(new RecyclerItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ArrayList<MenuProductOptionValueModel> optionValueList = menuProductOptionModel.getOptionValueModelList();
                    if(!optionValueList.get(position).isSelected()){
                        for(MenuProductOptionValueModel menuProductOptionValueModel : optionValueList){
                            menuProductOptionValueModel.setSelected(false);
                        }
                        optionValueList.get(position).setSelected(true);
                        productRadioOptionsRecyclerAdapter.notifyDataSetChanged();
                        productPriceTextView.setText(PriceHelper.calculatePriceAfterRadioOptionValueChanged(
                                productCount, menuProductModel, optionValueList.get(position)));
                    }
                }
            });
            recyclerView.setAdapter(productRadioOptionsRecyclerAdapter);
            headerTextView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
        else{

            final ProductCheckboxOptionsRecyclerAdapter productCheckboxOptionsRecyclerAdapter =
                    new ProductCheckboxOptionsRecyclerAdapter(menuProductOptionModel.getOptionValueModelList());
            productCheckboxOptionsRecyclerAdapter.setRecyclerItemClickListener(new RecyclerItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ArrayList<MenuProductOptionValueModel> optionValueList = menuProductOptionModel.getOptionValueModelList();
                    optionValueList.get(position).setSelected(
                            !optionValueList.get(position).isSelected());
                    productCheckboxOptionsRecyclerAdapter.notifyItemChanged(position);
                    productPriceTextView.setText(
                            PriceHelper.calculatePriceAfterCheckboxOptionValueChanged(
                                    productCount, menuProductModel, optionValueList));
                }
            });
            recyclerView.setAdapter(productCheckboxOptionsRecyclerAdapter);
            headerTextView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void setFields(){
        TextHelper.setTextFromHTML(productDescriptionTextView, menuProductModel.getDescription());
        ImageLoadHelper.loadImage(productImageView, menuProductModel.getImageURL());
        productNameTextView.setText(menuProductModel.getName());
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
        /*
        if(menuProductModel.getId().equals(String.valueOf(ApiConstants.PRODUCT_ID_WUNSCHPIZZA))){
            wunschpizzaAlertTextView.setVisibility(View.VISIBLE);
        }
        else {
            wunschpizzaAlertTextView.setVisibility(View.GONE);
        }
        */
    }

    private void fixRadioAndCheckbox(){
        if(menuProductModel.getId().equals(String.valueOf(ApiConstants.PRODUCT_ID_ABEND_MENU)) ||
                menuProductModel.getId().equals(String.valueOf(ApiConstants.PRODUCT_ID_MITTAGS_MENU))){
            for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
                boolean isAbendMenuPizzaSelection =
                        menuProductOptionModel.getOptionId().equals(ApiConstants.OPTION_ID_ABEND_AND_MITTAGS_MENU_PIZZA_SELECTION) &&
                                menuProductOptionModel.getProductOptionId().equals(ApiConstants.PRODUCT_OPTION_ID_ABEND_MENU_PIZZA_SELECTION);
                boolean isMittagsMenuPizzaSelection =
                        menuProductOptionModel.getOptionId().equals(ApiConstants.OPTION_ID_ABEND_AND_MITTAGS_MENU_PIZZA_SELECTION) &&
                                menuProductOptionModel.getProductOptionId().equals(ApiConstants.PRODUCT_OPTION_ID_MITTAGS_MENU_OPTIONS);
                if(isAbendMenuPizzaSelection || isMittagsMenuPizzaSelection){
                    menuProductOptionModel.setType("radio");
                }
            }
        }

        ArrayList<MenuProductOptionModel> sortedOptionList = menuProductModel.getProductOptionList();
        Collections.sort(
                sortedOptionList,
                new Comparator<MenuProductOptionModel>() {
                    @Override
                    public int compare(MenuProductOptionModel o1, MenuProductOptionModel o2) {
                        //return o2.getType().compareTo(o1.getType());
                        //return o1.getOptionValueModelList().size() - o2.getOptionValueModelList().size();
                        return o1.getOrder() - o2.getOrder();
                    }
                });
        menuProductModel.setProductOptionList(sortedOptionList);
    }

    private void setSelectedPriceShowingOptions(MenuProductOptionModel menuProductOptionModel){
        for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionModel.getOptionValueModelList()){
            if(menuProductOptionValueModel.getPrice().equals("0") || menuProductOptionValueModel.getPrice().equals("0.00")){

                /*
                //checkbox
                if(!(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                        menuProductOptionModel.getType().toLowerCase().equals("select"))){
                    menuProductOptionValueModel.setSelected(true);
                }

                //radio
                else if(!isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList())){
                    menuProductOptionValueModel.setSelected(true);
                }
                */

                boolean isRadio = menuProductOptionModel.getType().toLowerCase().equals("radio") || menuProductOptionModel.getType().toLowerCase().equals("select");
                boolean isAnyOptionValueSelected = isAnyOptionValueSelected(menuProductOptionModel.getOptionValueModelList());
                if(isRadio && !isAnyOptionValueSelected){
                    menuProductOptionValueModel.setSelected(true);
                }
            }
        }
    }

    private void addProductToCart(){

        DialogHelper.showLoadingDialog();
        Call<ResponseObject<AddProductToBasketResponseModel>> call =
                ApiService.apiInterface.addProductsToBasket(
                        "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_ADD_PRODUCTS_TO_BASKET + SessionHelper.getCustomerToken().getToken(),
                        getAddToCartRequestParams());
        call.enqueue(new Callback<ResponseObject<AddProductToBasketResponseModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<AddProductToBasketResponseModel>> call, Response<ResponseObject<AddProductToBasketResponseModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() && response.body().getData() != null){
                    if(response.body().isSuccess()){
                        getCartItemCount(response.body().getData().getSuccessMessage());
                    }
                    else
                        DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, response.body().getData().getErrorMessage());
                }
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<ResponseObject<AddProductToBasketResponseModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });

    }

    private RequestBody getAddToCartRequestParams(){

        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("product_id", menuProductModel.getId());
        formBodyBuilder.add("quantity", String.valueOf(productCount));

        for(MenuProductOptionModel productOptionModel : menuProductModel.getProductOptionList()){
            ArrayList<String> selectedCheckboxOptionList = new ArrayList<>();
            for(MenuProductOptionValueModel productOptionValueModel : productOptionModel.getOptionValueModelList()){
                if(productOptionValueModel.isSelected()){
                    if(productOptionModel.getType().toLowerCase().equals("checkbox")){
                        selectedCheckboxOptionList.add(productOptionValueModel.getProductOptionValueId());
                    }
                    else {
                        String key = "option[" + productOptionModel.getProductOptionId() + "]";
                        formBodyBuilder.add(key, productOptionValueModel.getProductOptionValueId());
                    }
                }
            }
            if(productOptionModel.getType().toLowerCase().equals("checkbox")){
                for(int i = 0; i < selectedCheckboxOptionList.size(); i++){
                    String key = "option[" + productOptionModel.getProductOptionId() + "][" + String.valueOf(i) + "]";
                    formBodyBuilder.add(key, selectedCheckboxOptionList.get(i));
                }
            }
        }

        return formBodyBuilder.build();
    }


    private void getCartItemCount(final String dialogMessage){
        /*
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken());
                */

        HashMap<String, Object> params = new HashMap<>();
        SessionHelper.addCouponCodeToRequestParamsIfNeeded(params);

        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_GET_CART_PRODUCTS + SessionHelper.getCustomerToken().getToken(),
                params);

        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getCartTotalModel().getText()));

                    DialogHelper.showOneButtonDialogWithCallback(
                            dialogMessage,
                            new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            },
                            false);
                }

            }

            @Override
            public void onFailure(Call<ResponseObject<CartInfoModel>> call, Throwable t) {

            }
        });
    }


    private boolean checkFields(){
        for(int i = 0; i < menuProductModel.getProductOptionList().size(); i++){
            MenuProductOptionModel menuProductOptionValueModel = menuProductModel.getProductOptionList().get(i);
            boolean isRadio = menuProductOptionValueModel.getType().toLowerCase().equals("radio") || menuProductOptionValueModel.getType().toLowerCase().equals("select");
            if(isRadio && !isSelectedAtLeastOne(menuProductModel.getProductOptionList().get(i).getOptionValueModelList())){
                DialogHelper.showAlertDialog(BaseActivity.currentActivity,
                        menuProductModel.getProductOptionList().get(i).getName() + " " + noOptionsSelectedText);
                return false;
            }
        }
        return true;
    }

    private boolean isSelectedAtLeastOne(ArrayList<MenuProductOptionValueModel> menuProductOptionValueModels){
        for(MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionValueModels){
            if(menuProductOptionValueModel.isSelected()){
                return true;
            }
        }
        return false;
    }

    private boolean isAnyOptionValueSelected(ArrayList<MenuProductOptionValueModel> menuProductOptionValueModels){
        for (MenuProductOptionValueModel menuProductOptionValueModel : menuProductOptionValueModels){
            if(menuProductOptionValueModel.isSelected()){
                return true;
            }
        }
        return false;
    }

}

