package ch.pizzalink.android.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.pizzalink.android.R;
import ch.pizzalink.android.activity.BaseActivity;
import ch.pizzalink.android.activity.MainActivity;
import ch.pizzalink.android.adapter.recycler.ProductCheckboxOptionsRecyclerAdapter;
import ch.pizzalink.android.adapter.recycler.ProductRadioOptionsRecyclerAdapter;
import ch.pizzalink.android.api.ApiEndPoints;
import ch.pizzalink.android.api.ApiErrorUtils;
import ch.pizzalink.android.api.ApiService;
import ch.pizzalink.android.api.ResponseObject;
import ch.pizzalink.android.helper.DialogHelper;
import ch.pizzalink.android.helper.ImageLoadHelper;
import ch.pizzalink.android.helper.PriceHelper;
import ch.pizzalink.android.helper.SessionHelper;
import ch.pizzalink.android.helper.SharedPrefsHelper;
import ch.pizzalink.android.interfaces.RecyclerItemClickListener;
import ch.pizzalink.android.model.AddProductToBasketResponseModel;
import ch.pizzalink.android.model.cart.CartInfoModel;
import ch.pizzalink.android.model.menu.MenuProductModel;
import ch.pizzalink.android.model.menu.MenuProductOptionModel;
import ch.pizzalink.android.model.menu.MenuProductOptionValueModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cimenmus on 08/10/2017.
 */

public class ProductPropertiesBottomSheetDialog extends BottomSheetDialogFragment {

    @BindView(R.id.closeImageView) ImageView closeImageView;
    @BindView(R.id.productImageView) ImageView productImageView;
    @BindView(R.id.productNameTextView) TextView productNameTextView;
    @BindView(R.id.productPriceTextView) TextView productPriceTextView;
    @BindView(R.id.addToCartButton) Button addToCartButton;
    @BindView(R.id.radioRecyclerHeaderTextView) TextView radioRecyclerHeaderTextView;
    @BindView(R.id.radioRecyclerView) RecyclerView radioRecyclerView;
    @BindView(R.id.checkboxRecyclerHeaderTextView) TextView checkboxRecyclerHeaderTextView;
    @BindView(R.id.checkboxRecyclerView) RecyclerView checkboxRecyclerView;
    @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 BottomSheetBehavior mBehavior;
    private MenuProductModel menuProductModel;

    private ArrayList<MenuProductOptionValueModel> productRadioOptionValueList = new ArrayList<>();
    private ArrayList<MenuProductOptionValueModel> productCheckboxOptionValueList = new ArrayList<>();
    private ProductRadioOptionsRecyclerAdapter productRadioOptionsRecyclerAdapter;
    private ProductCheckboxOptionsRecyclerAdapter productCheckboxOptionsRecyclerAdapter;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        View view = View.inflate(getContext(), R.layout.layout_bottomsheet, null);
        ButterKnife.bind(this, view);
        initViews();
        dialog.setContentView(view);
        mBehavior = BottomSheetBehavior.from((View) view.getParent());
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    @OnClick({R.id.closeImageView,
            R.id.increaseProductCountImageView,
            R.id.deccreaseProductCountImageView,
            R.id.addToCartButton})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.closeImageView:
                dismiss();
                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())
                    //addProductToCart();
                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);
                    }

                }
            }
        }

    }

    private void initViews(){
        setFields();
        fillRadioAndCheckboxOptionLists();
        switch (menuProductModel.getProductOptionType()){
            case RADIO_AND_CHECKBOX:
                radioRecyclerView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.VISIBLE);
                radioRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                checkboxRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                initRadioRecyclerView();
                initCheckboxRecyclerView();
                break;
            case RADIO:
                radioRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                radioRecyclerView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.GONE);
                checkboxRecyclerHeaderTextView.setVisibility(View.GONE);
                initRadioRecyclerView();
                break;
            case CHECKBOX:
                radioRecyclerHeaderTextView.setVisibility(View.GONE);
                radioRecyclerView.setVisibility(View.GONE);
                checkboxRecyclerHeaderTextView.setVisibility(View.VISIBLE);
                checkboxRecyclerView.setVisibility(View.VISIBLE);
                initCheckboxRecyclerView();
                break;
        }
    }

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

    private void initRadioRecyclerView(){
        radioRecyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(BaseActivity.currentActivity, 1);
        radioRecyclerView.setLayoutManager(gridLayoutManager);
        productRadioOptionsRecyclerAdapter = new ProductRadioOptionsRecyclerAdapter(productRadioOptionValueList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(!productRadioOptionValueList.get(position).isSelected()){
                    for(MenuProductOptionValueModel menuProductOptionValueModel : productRadioOptionValueList){
                        menuProductOptionValueModel.setSelected(false);
                    }
                    productRadioOptionValueList.get(position).setSelected(true);
                    productRadioOptionsRecyclerAdapter.notifyDataSetChanged();
                    productPriceTextView.setText(PriceHelper.calculatePriceAfterRadioOptionValueChanged(
                            productCount, menuProductModel, productRadioOptionValueList.get(position)));
                }
            }
        });
        radioRecyclerView.setAdapter(productRadioOptionsRecyclerAdapter);
    }

    private void initCheckboxRecyclerView(){
        checkboxRecyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(BaseActivity.currentActivity, 1);
        checkboxRecyclerView.setLayoutManager(gridLayoutManager);
        productCheckboxOptionsRecyclerAdapter = new ProductCheckboxOptionsRecyclerAdapter(productCheckboxOptionValueList, new RecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                productCheckboxOptionValueList.get(position).setSelected(
                        !productCheckboxOptionValueList.get(position).isSelected());
                productCheckboxOptionsRecyclerAdapter.notifyItemChanged(position);
                productPriceTextView.setText(
                        PriceHelper.calculatePriceAfterCheckboxOptionValueChanged(
                                productCount, menuProductModel, productCheckboxOptionValueList));
            }
        });
        checkboxRecyclerView.setAdapter(productCheckboxOptionsRecyclerAdapter);
    }

    private void setFields(){
        ImageLoadHelper.loadImage(productImageView, menuProductModel.getImageURL());
        productNameTextView.setText(menuProductModel.getName());
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
        productPriceTextView.setText(PriceHelper.getPriceWithCurreny(menuProductModel.getPrice()));
    }

    private void fillRadioAndCheckboxOptionLists(){
        for(MenuProductOptionModel menuProductOptionModel : menuProductModel.getProductOptionList()){
            setSelectedPriceShowingOptions(menuProductOptionModel);

            if(menuProductOptionModel.getType().toLowerCase().equals("radio") ||
                    menuProductOptionModel.getType().toLowerCase().equals("select")){
                radioRecyclerHeaderTextView.setText(menuProductOptionModel.getName());
                productRadioOptionValueList.addAll(menuProductOptionModel.getOptionValueModelList());
            }
            else{
                checkboxRecyclerHeaderTextView.setText(menuProductOptionModel.getName());
                productCheckboxOptionValueList.addAll(menuProductOptionModel.getOptionValueModelList());
            }
        }
    }

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

    /*
    private void addProductToCart(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<AddProductToBasketResponseModel>> call =
                ApiService.apiInterface.addProductsToBasket(
                        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()){
                        DialogHelper.showDialogWithPositiveButton(BaseActivity.currentActivity, response.body().getData().getSuccessMessage());
                        getCartItemCount();
                    }
                    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 HashMap<String, Object> getAddToCartRequestParams(){

        HashMap<String, Object> params = new HashMap<>();
        params.put("product_id", menuProductModel.getId());
        params.put("quantity", productCount);

        for(MenuProductOptionModel productOptionModel : menuProductModel.getProductOptionList()){

            ArrayList<String> selectedCheckboxOptionList = new ArrayList<>();

            for(MenuProductOptionValueModel productOptionValueModel : productOptionModel.getOptionValueModelList()){

                if(productOptionValueModel.isSelected()){

                    if(productOptionModel.getType().equals("checkbox")){
                        selectedCheckboxOptionList.add(productOptionValueModel.getProductOptionValueId());
                    }
                    else {
                        params.put("option[" + productOptionModel.getProductOptionId() + "]", productOptionValueModel.getProductOptionValueId());
                    }
                }
            }

            if(productOptionModel.getType().equals("checkbox")){
                params.put("option[" + productOptionModel.getProductOptionId() + "]", selectedCheckboxOptionList);
            }

        }

        return params;
    }

    private void getCartItemCount(){
        Call<ResponseObject<CartInfoModel>> call = ApiService.apiInterface.getCartProducts(
                SessionHelper.getCustomerToken().getToken());
        call.enqueue(new Callback<ResponseObject<CartInfoModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<CartInfoModel>> call, Response<ResponseObject<CartInfoModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess()){
                    SharedPrefsHelper.setCartItemCount(response.body().getData().getProducts().size());
                    SharedPrefsHelper.setCartTotalPrice(PriceHelper.removeCurrencyFromPrice(response.body().getData().getTotals().get(0).getText()));
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.setCartItemCount();
                    dismiss();
                }
            }

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

            }
        });
    }


    private boolean checkFields(){

        if(radioRecyclerView.getVisibility() == View.VISIBLE &&
                !isSelectedAtLeastOne(productRadioOptionValueList)){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity,
                    radioRecyclerHeaderTextView.getText().toString() + " " + noOptionsSelectedText);
            return false;
        }

        if(checkboxRecyclerView.getVisibility() == View.VISIBLE &&
                !isSelectedAtLeastOne(productCheckboxOptionValueList)){
            DialogHelper.showAlertDialog(BaseActivity.currentActivity,
                    checkboxRecyclerHeaderTextView.getText().toString() + " " + 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;
    }

}
