package com.yono.messeripos;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textview.MaterialTextView;
import com.yono.messeripos.adapter.CartAdapter;
import com.yono.messeripos.api.client.Client;
import com.yono.messeripos.api.service.OrdersService;
import com.yono.messeripos.api.service.PaymentService;
import com.yono.messeripos.models.MainViewModelsCart;
import com.yono.messeripos.models.PaymentPending;
import com.yono.messeripos.models.PaymentsModels;
import com.yono.messeripos.models.ProductCartModels;
import com.yono.messeripos.models.ProductModels;
import com.yono.messeripos.models.VaNumberModels;
import com.yono.messeripos.response.DataResponse;
import com.yono.messeripos.response.OrdersResponse;
import com.yono.messeripos.utils.Utils;

import java.util.List;
import java.util.Objects;

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

import static com.yono.messeripos.MainActivity.ORDER_ID;
import static com.yono.messeripos.MainActivity.orderId;

public class CartActivity extends AppCompatActivity {

    CartAdapter cartAdapter;
    MainViewModelsCart modelsCart;
    RecyclerView recyclerView;
    List<ProductCartModels> dataCart = null;
    public static Boolean statusPost;
    SharedPreferences sharedPreferences;

    ImageView cartEmptyImage;
    MaterialTextView cartEmptyText;
    public static MaterialTextView grandToral;
    Utils utils = new Utils();
    MaterialButton btnSaveCart;
    Button btnCheckout;
    CardView cardView;
    PaymentsModels paymentsModelsIntent;
    public static final String CODE_SEND_CHECKOUT_HISTORY = "data_hcheckout_history";

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        btnSaveCart = findViewById(R.id.btSave);
        cartEmptyImage = findViewById(R.id.cartEmpty);
        cartEmptyText = findViewById(R.id.cartEmptyText);
        recyclerView = findViewById(R.id.rvCart);
        btnCheckout = findViewById(R.id.btCheckout);
        cardView = findViewById(R.id.cardviews);

        // set visibility gone for cartEmpty
        cartEmptyImage.bringToFront();
        cartEmptyText.bringToFront();
        cartEmptyImage.setVisibility(View.GONE);
        cartEmptyText.setVisibility(View.GONE);

        Window w = getWindow();
        w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        sharedPreferences = getSharedPreferences(MainActivity.MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);

        MaterialToolbar toolbars = findViewById(R.id.cAppBar);
        setSupportActionBar(toolbars);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Cart");
        toolbars.setNavigationOnClickListener(view -> onBackPressed());

        modelsCart = new ViewModelProvider(this).get(MainViewModelsCart.class);
        paymentsModelsIntent = getIntent().getParcelableExtra(HistoryActivity.DATA_TRANSACTION_PENDING);


//        actionSaveCart();
        btnSaveCart.setOnClickListener(view -> actionSaveCart());

        cartAdapter = new CartAdapter();
        LinearLayoutManager llm = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(llm);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        recyclerView.addItemDecoration(dividerItemDecoration);

//        show to cart
        Log.i("GET CART", "onCreate: "+utils.convertGson(paymentsModelsIntent));
        if (paymentsModelsIntent == null){
            modelsCart = new ViewModelProvider(this).get(MainViewModelsCart.class);
            modelsCart.getCartById(sharedPreferences.getString(ORDER_ID,"")).observe(this, new Observer<List<ProductCartModels>>() {
                @Override
                public void onChanged(List<ProductCartModels> productCartModels) {
                    Log.i("TAG", "onChanged: "+utils.convertGson(productCartModels));
                    if (!productCartModels.isEmpty()) {
                        Log.i("TAG_DALAM", "onChanged: "+sharedPreferences.getString(ORDER_ID, ""));
                        dataCart = productCartModels;
                        cartAdapter.setCartAdapter(CartActivity.this, productCartModels);
                        recyclerView.setAdapter(cartAdapter);
                    }else {
                        Log.i("TAG_LUAR", "onChanged: "+utils.convertGson(productCartModels));
                        cartEmptyText.setVisibility(View.VISIBLE);
                        cartEmptyImage.setVisibility(View.VISIBLE);
                        cardView.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.GONE);
                    }
                }
            });
        }else{
            Log.i("ADA_DATA", "onCreate: "+utils.convertGson(paymentsModelsIntent));
            modelsCart.getCartById(paymentsModelsIntent.getOrderId()).observe(this, new Observer<List<ProductCartModels>>() {
                @Override
                public void onChanged(List<ProductCartModels> productCartModels) {
                    if (!productCartModels.isEmpty()) {
                        dataCart = productCartModels;
                        cartAdapter.setCartAdapter(CartActivity.this, productCartModels);
                        recyclerView.setAdapter(cartAdapter);
                    }else {
                        cartEmptyText.setVisibility(View.VISIBLE);
                        cartEmptyImage.setVisibility(View.VISIBLE);
                        cardView.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.GONE);
                    }
                }
            });


        }



        cartAdapter.setListener(new CartAdapter.CartListener() {
            @Override
            public void onDelete(ProductCartModels productCartModels) {
                modelsCart.deleteCart(productCartModels);
            }

            @Override
            public void onUpdateQuantityPlus(ProductCartModels productCartModels) {
                if (!((productCartModels.getQuantity_orders() + 1) > productCartModels.getQuantity_stock() - 1)){
                    productCartModels.setQuantity_orders(productCartModels.getQuantity_orders() + 1);
                    modelsCart.updateCart(productCartModels);
                }else{
                    utils.dialog(CartActivity.this,
                            true,
                            "Warning",
                            "Item stock does not meet").show();
                }

            }

            @Override
            public void onUpdateQuantityMinus(ProductCartModels productCartModels) {
                if (productCartModels.getQuantity_orders() > 1) {
                    productCartModels.setQuantity_orders(productCartModels.getQuantity_orders() - 1);
                    modelsCart.updateCart(productCartModels);
                }
            }

            @Override
            public void onCheckout(ProductCartModels productCartModels) {
            }
        });

        btnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ProgressDialog progressDialog = new ProgressDialog(CartActivity.this);
                progressDialog.setMessage("Creating your orders....");
                progressDialog.show();

                OrdersResponse ordersResponse = new OrdersResponse();
                List<ProductCartModels> productCartModels;
                Log.d("Data cart checkout", "onClick: " + dataCart);
                for (ProductCartModels pd : dataCart) {
                    ordersResponse.setOrders_id(pd.getId_orders());
                }
                ordersResponse.setProduct_cart(dataCart);
                modelsCart.insertOrders(ordersResponse);
                progressDialog.dismiss();


                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean(MainActivity.CHECKOUT, true);
                if(editor.commit()){
                    Log.i("FROM_CHECKOUT_INTENT", "onClick: "+utils.convertGson(paymentsModelsIntent));
                    if (paymentsModelsIntent != null){
                        Log.i("TAGAAAAA", "onClick: "+utils.convertGson(paymentsModelsIntent));
                        startActivity(new Intent(CartActivity.this, MethodePayment.class)
                                .putExtra(CODE_SEND_CHECKOUT_HISTORY, paymentsModelsIntent));
                    }else{
                        startActivity(new Intent(CartActivity.this, MethodePayment.class));
                        finish();
                    }
                }
            }
        });

    }

    private void actionSaveCart() {
        ProgressDialog progressDialog = new ProgressDialog(CartActivity.this);
        progressDialog.setMessage("Creating your orders....");
        progressDialog.show();
        Client client = new Client();
        modelsCart.getCartById(sharedPreferences.getString(ORDER_ID, "")).observe(this, new Observer<List<ProductCartModels>>() {
            @Override
            public void onChanged(List<ProductCartModels> productCartModels) {
                long grossAmount = 0;
                PaymentPending paymentPending = new PaymentPending();

                for (ProductCartModels pd:productCartModels){
                    grossAmount = grossAmount + (pd.getQuantity_orders()*pd.getPrice_orders());
                    paymentPending.setGross_amount(grossAmount);
                }
//                Log.i("ORDER_ID_SAVE", "onCreate: "+sharedPreferences.getString(ORDER_ID,"").toString());
//                paymentsModels.setBank("");
//                paymentsModels.setPaymentType("pending");
//                paymentPending.setTransaction_status("pending");
                paymentPending.setId_orders(sharedPreferences.getString(ORDER_ID, ""));
                paymentPending.setTransaction_time(utils.dateNow());
                Log.i("Convert Input", "onChanged: "+utils.convertGson(paymentPending));
                modelsCart.savePaymentPending(paymentPending);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(ORDER_ID, "");
                if (editor.commit()){
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                            startActivity(new Intent(CartActivity.this, MainActivity.class));
                            finish();
                        }
                    }, 700);
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (sharedPreferences.getString(ORDER_ID, "") == null){
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(ORDER_ID, "MES-ORDER"+utils.timeStamp());
            editor.commit();
        }
        super.onBackPressed();
    }
}



/**
 * Bug ketika qty kurang dari stock masih bertambah
 *
 */