package com.yono.messeripos;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
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.yono.messeripos.adapter.CheckoutAdapter;
import com.yono.messeripos.api.client.Client;
import com.yono.messeripos.api.service.PaymentService;
import com.yono.messeripos.models.MainViewModelsCart;
import com.yono.messeripos.models.PaymentsModels;
import com.yono.messeripos.models.ProductCartModels;
import com.yono.messeripos.models.VaNumberModels;
import com.yono.messeripos.response.DataResponse;
import com.yono.messeripos.utils.Utils;

import java.util.List;

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

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

public class TransactionDetail extends AppCompatActivity {

    PaymentsModels paymentsModelsBank, paymentsModelsCash, paymentsModelsNfc;
    MainViewModelsCart mainViewModelsCart;
    String ordersId, payment, nama_bank;
    Utils utils = new Utils();
    RecyclerView recyclerView;
    CheckoutAdapter checkoutAdapter;
    TextView paymentMethode, grossAmountMethod, grossAmount, namaBank;
    MaterialButton btnConfirm;
    ProgressDialog progressDialog;
    Client client = new Client();
    PaymentService paymentService;
    SharedPreferences sharedPreferences, sharedPreferencesNfc;
    PaymentCreated paymentCreated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_transaction);

        recyclerView = findViewById(R.id.lvDetail);
        paymentMethode = findViewById(R.id.jenisMethod);
        grossAmountMethod = findViewById(R.id.mtdGrossAmount);
        grossAmount = findViewById(R.id.grossAmount);
        namaBank = findViewById(R.id.jenisTransfer);
        btnConfirm = findViewById(R.id.btnConfirm);


        progressDialog = new ProgressDialog(TransactionDetail.this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);

        MaterialToolbar toolbars = findViewById(R.id.appBarDetailTransaction);
        setSupportActionBar(toolbars);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Transaction Detail");
        toolbars.setNavigationOnClickListener(view -> onBackPressed());

        mainViewModelsCart = new ViewModelProvider(this).get(MainViewModelsCart.class);
        checkoutAdapter = new CheckoutAdapter();
        paymentCreated = new PaymentCreated();
        paymentCreated.setCancelable(false);
        sharedPreferences = getSharedPreferences(MainActivity.MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        sharedPreferencesNfc = getSharedPreferences(ScannerNfc.MY_SHARED_NFC, Context.MODE_PRIVATE);

        Log.i("LOGNFC", "onCreate: "+sharedPreferencesNfc.getString(ScannerNfc.NFC_ID, ""));
        paymentsModelsBank = getIntent().getParcelableExtra(PaymentActivity.PAYMENT_VIA_BANK);
        paymentsModelsCash = getIntent().getParcelableExtra(MethodePayment.VIA_CASH);
        paymentsModelsNfc = getIntent().getParcelableExtra(MethodePayment.VIA_NFC);

        Log.i("LOGNFCPINDAH", ""+utils.convertGson(paymentsModelsNfc));


        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

        getListTransaction();

        btnConfirm.setOnClickListener(view -> confirm());

    }

    private void getListTransaction() {
        if (paymentsModelsBank != null){
            grossAmount.setText(utils.convertPrice("Rp. ", paymentsModelsBank.getGrossAmount()));
            grossAmountMethod.setText(utils.convertPrice("Rp. ", paymentsModelsBank.getGrossAmount()));
            namaBank.setText(paymentsModelsBank.getBank().toUpperCase());
            paymentMethode.setText("Bank Transfer".toString());
            ordersId = paymentsModelsBank.getOrderId();
        } else if (paymentsModelsCash != null){
            grossAmount.setText(utils.convertPrice("Rp. ", paymentsModelsCash.getGrossAmount()));
            grossAmountMethod.setText(utils.convertPrice("Rp. ", paymentsModelsCash.getGrossAmount()));
            namaBank.setText(paymentsModelsCash.getBank().toUpperCase());
            paymentMethode.setText("Cash".toString());
            ordersId = paymentsModelsCash.getOrderId();
        } else if (paymentsModelsNfc != null){
            grossAmount.setText(utils.convertPrice("Rp. ", paymentsModelsNfc.getGrossAmount()));
            grossAmountMethod.setText(utils.convertPrice("Rp. ", paymentsModelsNfc.getGrossAmount()));
            namaBank.setText(paymentsModelsCash.getBank().toUpperCase());
            paymentMethode.setText("NFC Tap".toString());
            ordersId = paymentsModelsNfc.getOrderId();
        }
        mainViewModelsCart.getCartById(ordersId).observe(this, new Observer<List<ProductCartModels>>() {
            @Override
            public void onChanged(List<ProductCartModels> productCartModels) {
                Log.i("GET ALL PRODUCT", "onChanged: "+utils.convertGson(productCartModels));
                checkoutAdapter.setCheckoutAdapter(TransactionDetail.this, productCartModels);
                recyclerView.setAdapter(checkoutAdapter);
            }
        });
    }

    private void confirm() {
        progressDialog.show();
        if (paymentsModelsBank != null){
            paymentService = client.Client(PaymentService.class);
            paymentService.postFromCart(paymentsModelsBank).enqueue(new Callback<DataResponse<PaymentsModels<List<VaNumberModels>>>>() {
                @Override
                public void onResponse(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Response<DataResponse<PaymentsModels<List<VaNumberModels>>>> response) {
                                if (response.body() != null){
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString(ORDER_ID, "");
                                    editor.putBoolean(CHECKOUT, false);
                                    progressDialog.dismiss();
                                    if (editor.commit()){
                                        paymentCreated.show(getSupportFragmentManager(),"paymentCreated");
                                    }
                                }else{
                                    progressDialog.dismiss();
                                    new AlertDialog.Builder(TransactionDetail.this)
                                            .setTitle("Payment Order")
                                            .setMessage("Erorr save!").show();
                                }
                }

                @Override
                public void onFailure(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Throwable t) {
                    progressDialog.dismiss();
                    new AlertDialog.Builder(TransactionDetail.this)
                            .setTitle("Payment Order")
                            .setMessage("Erorr save!").show();
                }
            });
        }else if (paymentsModelsCash != null){
            paymentService = client.Client(PaymentService.class);
            paymentService.postFromCart(paymentsModelsCash).enqueue(new Callback<DataResponse<PaymentsModels<List<VaNumberModels>>>>() {
                @Override
                public void onResponse(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Response<DataResponse<PaymentsModels<List<VaNumberModels>>>> response) {
                    if (response.body() != null){
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(ORDER_ID, "");
                        editor.putBoolean(CHECKOUT, false);
                        progressDialog.dismiss();
                        if (editor.commit()){
                            paymentCreated.show(getSupportFragmentManager(),"paymentCreated");
                        }
                    }else{
                        progressDialog.dismiss();
                        new AlertDialog.Builder(TransactionDetail.this)
                                .setTitle("Payment Order")
                                .setMessage("Erorr save!").show();
                    }
                }

                @Override
                public void onFailure(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Throwable t) {
                    progressDialog.dismiss();
                    new AlertDialog.Builder(TransactionDetail.this)
                            .setTitle("Payment Order")
                            .setMessage("Erorr save!").show();
                }
            });
        }else if (paymentsModelsNfc != null){
            paymentService = client.Client(PaymentService.class);
            paymentService.postFromCart(paymentsModelsNfc).enqueue(new Callback<DataResponse<PaymentsModels<List<VaNumberModels>>>>() {
                @Override
                public void onResponse(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Response<DataResponse<PaymentsModels<List<VaNumberModels>>>> response) {
                    if (response.body() != null){
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(ORDER_ID, "");
                        editor.putBoolean(CHECKOUT, false);
                        progressDialog.dismiss();
                        if (editor.commit()){
                            paymentCreated.show(getSupportFragmentManager(),"paymentCreated");
                        }
                    }else{
                        progressDialog.dismiss();
                        new AlertDialog.Builder(TransactionDetail.this)
                                .setTitle("Payment Order")
                                .setMessage("Erorr save!").show();
                    }
                }

                @Override
                public void onFailure(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Throwable t) {
                    progressDialog.dismiss();
                    new AlertDialog.Builder(TransactionDetail.this)
                            .setTitle("Payment Order")
                            .setMessage("Erorr save!").show();
                }
            });
        }
    }
}
