package ch.pizzalemon.android.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.FragmentManager;
import androidx.cardview.widget.CardView;
import android.view.View;
import android.webkit.WebView;

import com.badoualy.stepperindicator.StepperIndicator;
import com.braintreepayments.api.DropInPaymentMethod;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzalemon.android.R;
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.fragment.createOrder.CreateOrderNoteFragment;
import ch.pizzalemon.android.fragment.createOrder.CreateOrderResultFragment;
import ch.pizzalemon.android.fragment.createOrder.CreateOrderSummaryFragment;
import ch.pizzalemon.android.fragment.createOrder.PaymentMethodFragment;
import ch.pizzalemon.android.fragment.createOrder.ShippingAddressFragment;
import ch.pizzalemon.android.fragment.createOrder.ShippingMethodFragment;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.model.AddressModel;
import ch.pizzalemon.android.model.PaymentMethodModel;
import ch.pizzalemon.android.model.PaymentTokenModel;
import ch.pizzalemon.android.model.ShippingMethodModel;
import ch.pizzalemon.android.model.cart.CartInfoModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CreateOrderActivity extends BaseActivity {

    @BindView(R.id.createOrderCardView) CardView createOrderCardView;
    @BindView(R.id.paymentWebView) WebView paymentWebView;
    @BindView(R.id.stepperIndicator) StepperIndicator stepperIndicator;

    private FragmentManager fragmentManager;

    private CartInfoModel cartInfoModel;
    private ShippingMethodModel selectedShippingMethod;
    private AddressModel selectedShippingAddress;
    private PaymentMethodModel selectedPaymentMethod;
    private Boolean slicePizza;
    private String orderNote;
    private String discountAmount;
    private String couponCode;
    private ArrayList<PaymentMethodModel> paymentMethodList = new ArrayList<>();

    private PaymentTokenModel paymentTokenModel = null;

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getDataFromIntent(){
        cartInfoModel = (CartInfoModel) getIntent().getSerializableExtra("cartInfoModel");
    }

    private void initViews(){
        fragmentManager = getSupportFragmentManager();
        initStepIndicator();
        openFragment(0);
    }

    private void initStepIndicator(){
        /*
        6 fragment var, ama sonuncu step'te tik göstersin diye step sayısını, fragment sayısı - 1 yaptık
         */
        stepperIndicator.setStepCount(5);
        /*
        stepperIndicator.addOnStepClickListener(new StepperIndicator.OnStepClickListener() {
            @Override
            public void onStepClicked(int step) {
                openFragment(step);
            }
        });
        */
    }

    private void openFragment(int position){
        switch (position){
            case 0:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        ShippingMethodFragment.newInstance()).commit();
                break;
            case 1:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        ShippingAddressFragment.newInstance()).commit();
                break;
            case 2:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        PaymentMethodFragment.newInstance()).commit();
                break;
            case 3:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        CreateOrderNoteFragment.newInstance()).commit();
                break;
            case 4:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        CreateOrderSummaryFragment.newInstance(paymentTokenModel)).commit();
                break;

            case 5:
                fragmentManager.beginTransaction().replace(R.id.orderFragmentsContainer,
                        CreateOrderResultFragment.newInstance()).commit();
                break;
        }
        stepperIndicator.setCurrentStep(position);
    }

    public void onNextClicked(String clickedFragmentName){
        switch (clickedFragmentName){
            case ShippingMethodFragment.FRAGMENT_NAME:
                openFragment(1);
                break;
            case ShippingAddressFragment.FRAGMENT_NAME:
                openFragment(2);
                break;
            case PaymentMethodFragment.FRAGMENT_NAME:
                openFragment(3);
                break;
            case CreateOrderNoteFragment.FRAGMENT_NAME:
                createBraintreePaymentTokenAndOpenSummaryFragment();
                break;
            case CreateOrderSummaryFragment.FRAGMENT_NAME:
                openFragment(5);
                break;
            case CreateOrderResultFragment.FRAGMENT_NAME:
                Intent mainActivityIntent = new Intent(this, MainActivity.class);
                mainActivityIntent.putExtra("isStartWithOrderHistory", true);
                startActivity(mainActivityIntent);
                SharedPrefsHelper.setCartItemCount(0);
                SharedPrefsHelper.setCartTotalPrice("0");
                finishAffinity();
                break;
        }
    }

    public void onPreviousClicked(String clickedFragmentName){
        switch (clickedFragmentName){
            case ShippingAddressFragment.FRAGMENT_NAME:
                openFragment(0);
                break;
            case PaymentMethodFragment.FRAGMENT_NAME:
                openFragment(1);
                break;
            case CreateOrderNoteFragment.FRAGMENT_NAME:
                openFragment(2);
                break;
            case CreateOrderSummaryFragment.FRAGMENT_NAME:
                openFragment(3);
                break;
        }
    }

    public CartInfoModel getCartInfo(){
        return cartInfoModel;
    }

    /**
     * Kampanya urunu detay sayfasında urunun fiyatı 0 olan tum optionlarını seçiyor,
     * bunun da düzeltilmesi gerekiyor!!
     */

    /**
     * eğer kampanya kullanıldıysa cartInfoModel de  isPizzaPassCampaignUsed
     * alanalrını true olarak set ediyoruz. create order ekranlarında herhangi bir yerde sepet sorgusu yapınca
     * buradaki cartInfoModel i de güncelliyoruz. fakat isPizzaPassCampaignUsed alanları
     * servisten gelmeyen değerler, bizim loaklde tuttuğumuz değişkenler. bu sebeple bu alanlar servisten hep false geliyor,
     * buradakinde true olsa bile değişkeni guncellediğimiz için bu alanlar kayboluyor. bunu engellemek için bu metodu yazdım.
     */
    public void setCartInfoSafeForCampaigns(CartInfoModel cartInfoModel) {
        cartInfoModel.setPizzaPassCampaignUsed(this.cartInfoModel.isPizzaPassCampaignUsed());
        this.cartInfoModel = cartInfoModel;
    }

    /*
    public void setCartInfo(CartInfoModel cartInfoModel) {
        this.cartInfoModel = cartInfoModel;
    }
    */

    public ShippingMethodModel getSelectedShippingMethod(){
        return selectedShippingMethod;
    }

    public void setSelectedShippingMethod(ShippingMethodModel selectedShippingMethod){
        this.selectedShippingMethod = selectedShippingMethod;
    }

    public AddressModel getSelectedShippingAddress(){
        return selectedShippingAddress;
    }

    public void setSelectedShippingAddress(AddressModel selectedShippingAddress){
        this.selectedShippingAddress = selectedShippingAddress;
    }

    public PaymentMethodModel getSelectedPaymentMethod(){
        return selectedPaymentMethod;
    }

    public void setSelectedPaymentMethod(PaymentMethodModel selectedPaymentMethod){
        this.selectedPaymentMethod = selectedPaymentMethod;
    }

    public void setSelectedPaymentMethodForBraintree(DropInPaymentMethod paymentMethodType){
        String paymentMethodCode = "";
        switch (paymentMethodType){
            case PAYPAL:
                paymentMethodCode = ApiConstants.PAYMENT_METHOD_CODE_PAYPAL;
                break;
            case GOOGLE_PAY:
                paymentMethodCode = ApiConstants.PAYMENT_METHOD_CODE_ANDROID_PAY;
                break;
            default:
                paymentMethodCode = ApiConstants.PAYMENT_METHOD_CODE_CREDIT_DEBIT_CARD;
                break;
        }
        for(PaymentMethodModel paymentMethodModel : paymentMethodList){
            if(paymentMethodModel.getCode().equalsIgnoreCase(paymentMethodCode)){
                selectedPaymentMethod = paymentMethodModel;
                break;
            }
        }
    }

    public String getOrderNote(){
        if(orderNote == null)
            orderNote = "";
        return orderNote;
    }

    public void setPaymentWebViewVisibility(final boolean show){
        if(show){
            createOrderCardView.setVisibility(View.GONE);
            paymentWebView.setVisibility(View.VISIBLE);
        }
        else {
            createOrderCardView.setVisibility(View.VISIBLE);
            paymentWebView.setVisibility(View.GONE);
        }
    }

    private void createBraintreePaymentTokenAndOpenSummaryFragment(){
        DialogHelper.showLoadingDialog();
        Call<ResponseObject<PaymentTokenModel>> call = ApiService.apiInterface.createBraintreePaymentToken(
                "/" + SessionHelper.getSelectedStore().getStoreName() + ApiEndPoints.API_CREATE_BRAINTREE_PAYMENT_TOKEN + SessionHelper.getCustomerToken().getToken());

        call.enqueue(new Callback<ResponseObject<PaymentTokenModel>>() {
            @Override
            public void onResponse(Call<ResponseObject<PaymentTokenModel>> call, Response<ResponseObject<PaymentTokenModel>> response) {
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess() &&
                        response.body().getData().getToken() != null){
                    paymentTokenModel = response.body().getData();
                    openFragment(4);
                }
                else {
                    ApiErrorUtils.parseError(response);
                }
            }

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

    /*
    @Override
    public void onBackPressed() {
        if(paymentWebView.getVisibility() == View.VISIBLE){
            if(paymentWebView.canGoBack()){
                paymentWebView.goBack();
            }
            else{
                setPaymentWebViewVisibility(false);
            }
        }
        else{
            super.onBackPressed();
        }
    }
    */

    public void setOrderNote(String orderNote){
        this.orderNote = orderNote;
    }

    public Boolean getSlicePizza() {
        return slicePizza;
    }

    public void setSlicePizza(Boolean slicePizza) {
        this.slicePizza = slicePizza;
    }

    public String getDiscountAmount() {
        return discountAmount;
    }

    public void setDiscountAmount(String discountAmount) {
        this.discountAmount = discountAmount;
    }

    public String getCouponCode() {
        return couponCode;
    }

    public void setCouponCode(String couponCode) {
        this.couponCode = couponCode;
    }

    public void setPaymentMethodList(ArrayList<PaymentMethodModel> paymentMethodList) {
        this.paymentMethodList = paymentMethodList;
    }

    public WebView getPaymentWebView() {
        return paymentWebView;
    }
}
