package com.yono.messeripos;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.Gson;
import com.yono.messeripos.adapter.CheckoutAdapter;
import com.yono.messeripos.adapter.PaymentAdapter;
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.response.PaymentResponse;
import com.yono.messeripos.utils.Utils;

import java.util.ArrayList;
import java.util.List;

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

import static com.yono.messeripos.BottomSheets.grossAmount;
import static com.yono.messeripos.MainActivity.CHECKOUT;
import static com.yono.messeripos.MainActivity.ORDER_ID;
import static com.yono.messeripos.MainActivity.checkout;
import static com.yono.messeripos.MainActivity.orderId;

public class PaymentActivity extends AppCompatActivity {

    private ArrayList<PaymentResponse> paymentResponses = new ArrayList<>();
    public static String methodPay="";
    private Button btnPay;
    private MainViewModelsCart mainViewModels;
    private PaymentsModels paymentsModels;
    private long total = 0;
    private Utils utils = new Utils();
    private RecyclerView recyclerView;
    private CheckoutAdapter checkoutAdapter;
    public static BottomSheets bottomSheet;
    public static PaymentCreated paymentCreated;
    public static SharedPreferences sharedPreferences;
    Button cashBtn;
    ProgressDialog progressDialog;
    BottomSheetBehavior bottomSheetBank;
    RelativeLayout qrcodeLayoutBank;
    PaymentsModels paymentsModelsIntent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);

        Log.i("Status Checkout payment", "onCreate: "+checkout);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow();
            w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

        recyclerView = findViewById(R.id.rvPayment);

        sharedPreferences = getSharedPreferences(MainActivity.MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        paymentsModelsIntent = getIntent().getParcelableExtra(CartActivity.CODE_SEND_CHECKOUT_HISTORY);


        paymentsModels = new PaymentsModels();
        checkoutAdapter = new CheckoutAdapter();
        progressDialog = new ProgressDialog(PaymentActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);

        MaterialToolbar toolbars = findViewById(R.id.appbar);
        setSupportActionBar(toolbars);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Bank Transfer");
        toolbars.setNavigationOnClickListener(view -> onBackPressed());


        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        mainViewModels = new ViewModelProvider(PaymentActivity.this).get(MainViewModelsCart.class);

        Log.i("IN_HISTORY", "onCreate: "+utils.convertGson(paymentsModelsIntent));

//        if (paymentsModelsIntent == null){
//            mainViewModels.getCartById(sharedPreferences.getString(ORDER_ID, "")).observe(this, new Observer<List<ProductCartModels>>() {
//                @Override
//                public void onChanged(List<ProductCartModels> productCartModels) {
//                    String js = new Gson().toJson(productCartModels);
//                    Log.i("On payment", "onChanged: "+js);
//
//                    for (ProductCartModels pd : productCartModels){
//                        total = total + pd.getPrice_orders()*pd.getQuantity_orders();
//                    }
//
//                    if (productCartModels.size() !=0){
//                        getSupportActionBar().setTitle(productCartModels.get(0).getId_orders());
//                        paymentsModels.setOrderId(productCartModels.get(0).getId_orders());
//                        paymentsModels.setGrossAmount(total);
//                        checkoutAdapter.setCheckoutAdapter(PaymentActivity.this, productCartModels);
//                        recyclerView.setLayoutManager(new LinearLayoutManager(PaymentActivity.this, RecyclerView.VERTICAL, false));
//                        recyclerView.setAdapter(checkoutAdapter);
//                        recyclerView.addItemDecoration(dividerItemDecoration);
////                        grandTotal.setText(utils.convertPrice("Rp. ", total));
//                    }
//                }
//            });
//        }else{
//            mainViewModels.getCartById(paymentsModelsIntent.getOrderId()).observe(this, new Observer<List<ProductCartModels>>() {
//                @Override
//                public void onChanged(List<ProductCartModels> productCartModels) {
//                    String js = new Gson().toJson(productCartModels);
//                    Log.i("On Intent_CHANGE", "onChanged: "+paymentsModelsIntent.getOrderId());
//
//                    for (ProductCartModels pd : productCartModels){
//                        total = total + pd.getPrice_orders()*pd.getQuantity_orders();
//                    }
//
//                    if (productCartModels.size() != 0){
//                        getSupportActionBar().setTitle(productCartModels.get(0).getId_orders());
//                        paymentsModelsIntent.setOrderId(productCartModels.get(0).getId_orders());
//                        paymentsModelsIntent.setGrossAmount(total);
//                        checkoutAdapter.setCheckoutAdapter(PaymentActivity.this, productCartModels);
//                        recyclerView.setLayoutManager(new LinearLayoutManager(PaymentActivity.this, RecyclerView.VERTICAL, false));
//                        recyclerView.setAdapter(checkoutAdapter);
//                        recyclerView.addItemDecoration(dividerItemDecoration);
////                        grandTotal.setText(utils.convertPrice("Rp. ", total));
//                    }
//
//                }
//            });
//        }

        bottomSheet = new BottomSheets(paymentsModels,0);

        RecyclerView rvPayment = findViewById(R.id.rvPayment);

        LinearLayoutManager llm = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        rvPayment.setLayoutManager(llm);

//        paymentResponses.add(new PaymentResponse("https://i.ibb.co/5c40mWX/cash-logo.png", "cash"));
        paymentResponses.add(new PaymentResponse("https://i.ibb.co/XCsdmmT/Bank-Mandiri-logo.png", "mandiri"));
        paymentResponses.add(new PaymentResponse("https://i.ibb.co/2n65nCT/bca-bank-central-asia.png", "bca"));
        paymentResponses.add(new PaymentResponse("https://i.ibb.co/RjJQT9K/BNI-logo.png", "bni"));
//        paymentResponses.add(new PaymentResponse("https://i.ibb.co/n1V3ZCf/Whats-App-Image-2020-09-01-at-14-50-13.jpg", "nfc"));

        PaymentAdapter adapter = new PaymentAdapter(paymentResponses, this);
        rvPayment.setAdapter(adapter);

        btnPay = findViewById(R.id.btnPay);

        adapter.setListener(paymentResponse -> {
            methodPay = paymentResponse.getBank();
            startActivity(new Intent(PaymentActivity.this, TransactionDetail.class));
//            btnPay.setEnabled(true);
        });

//        btnPay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (methodPay.equals("cash")){
//                    paymentsModels.setPaymentType("cash");
//                    paymentsModels.setTransactionStatus("success");
//                    paymentsModels.setTransaction_id(utils.timeStamp()+"-MES");
//                    paymentsModels.setTransaction_time(utils.timeStamp());
//                    Log.i("CASH", "onClick: "+utils.convertGson(paymentsModels));
//
//                    if (paymentsModelsIntent == null){
//                        bottomSheet = new BottomSheets(paymentsModels,0);
//                        bottomSheet.setCancelable(true);
//                        bottomSheet.show(getSupportFragmentManager(),
//                                "ModalBottomSheet");
//                    }else{
//                        bottomSheet = new BottomSheets(paymentsModelsIntent,1);
//                        bottomSheet.setCancelable(true);
//                        bottomSheet.show(getSupportFragmentManager(),
//                                "ModalBottomSheet");
//                    }
//
//                }else{
//
//                    progressDialog.show();
//                    progressDialog.setCancelable(false);
////                    bottomSheetBank.setState(BottomSheetBehavior.STATE_EXPANDED);
////                    progressDialog.show();
//                    Client client = new Client();
//                    paymentsModels.setPaymentType("bank_transfer");
//                    paymentsModels.setBank(methodPay);
//                    paymentsModels.setOrderIdUpdate(sharedPreferences.getString(ORDER_ID,""));
//                    paymentsModels.setOrderId(sharedPreferences.getString(ORDER_ID, ""));
//                    paymentsModels.setTransactionStatus("success");
//                    paymentsModels.setTransaction_id(utils.timeStamp()+"-MES");
//                    paymentsModels.setTransaction_time(utils.timeStamp());
//                    Log.i("BANK", "onClick: "+utils.convertGson(paymentsModels));
//                    PaymentService paymentService = client.Client(PaymentService.class);
//
//                    if (paymentsModelsIntent == null){
//                        paymentService.postFromCart(paymentsModels).enqueue(new Callback<DataResponse<PaymentsModels<List<VaNumberModels>>>>() {
//                            @Override
//                            public void onResponse(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Response<DataResponse<PaymentsModels<List<VaNumberModels>>>> response) {
//                                Log.i("Paymen_bank", "onResponse: "+utils.convertGson(response.body()));
//
//                                if (response.body() != null){
//                                    SharedPreferences.Editor editor = sharedPreferences.edit();
//                                    editor.putString(ORDER_ID, "");
//                                    editor.putBoolean(CHECKOUT, false);
//                                    progressDialog.dismiss();
//                                    if (editor.commit()){
//                                        paymentCreated = new PaymentCreated();
//                                        paymentCreated.setCancelable(false);
//                                        paymentCreated.show(
//                                                getSupportFragmentManager(),
//                                                "paymentCreated"
//                                        );
//                                    }
//                                }else{
//                                    progressDialog.dismiss();
//                                    new AlertDialog.Builder(PaymentActivity.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(PaymentActivity.this)
//                                        .setCancelable(false)
//                                        .setTitle("Payment Order")
//                                        .setMessage("Add new payment failed, try again!").show();
//                            }
//                        });
//                    }else{
//                        paymentService.postFromCartPending(paymentsModelsIntent.getOrderId(), paymentsModelsIntent).enqueue(new Callback<DataResponse>() {
//                            @Override
//                            public void onResponse(Call<DataResponse> call,
//                                                   Response<DataResponse> response) {
//                                Log.i("Paymen_bank_sa", "onResponse: "+utils.convertGson(response.body()));
//
//                                if (response.body() != null){
//                                    SharedPreferences.Editor editor = sharedPreferences.edit();
//                                    editor.putString(ORDER_ID, "");
//                                    editor.putBoolean(CHECKOUT, false);
//                                    progressDialog.dismiss();
//                                    if (editor.commit()){
//                                        paymentCreated = new PaymentCreated();
//                                        paymentCreated.setCancelable(false);
//                                        paymentCreated.show(
//                                                getSupportFragmentManager(),
//                                                "QRCode"
//                                        );
//                                    }
//                                }else{
//                                    progressDialog.dismiss();
//                                    new AlertDialog.Builder(PaymentActivity.this)
//                                            .setTitle("Payment Order")
//                                            .setMessage("Erorr save!").show();
//                                }
//                            }
//
//                            @Override
//                            public void onFailure(Call<DataResponse> call, Throwable t) {
//                                progressDialog.dismiss();
//                                new AlertDialog.Builder(PaymentActivity.this)
//                                        .setCancelable(false)
//                                        .setTitle("Payment Order")
//                                        .setMessage("Add new payment failed, try again!").show();
//                            }
//                        });
//                    }
//
//                }
//            }
//        });

//        bottomSheet.setListener(new BottomSheets.CashListener() {
//            @Override
//            public void onCash(PaymentsModels paymentsModels) {
//                progressDialog.show();
//                Client client = new Client();
//                PaymentsModels paymentsModels1 = new PaymentsModels(
//                        MainActivity.orderId,
//                        "cash",
//                        "none",
//                        grossAmount
//                );
//
//                PaymentService paymentService = client.Client(PaymentService.class);
//                paymentService.postFromCart(paymentsModels1).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){
//                            progressDialog.dismiss();
//                            SharedPreferences.Editor editor = sharedPreferences.edit();
//                            editor.putBoolean(CHECKOUT, false);
//                            editor.putString(orderId, "");
//                            if (editor.commit()){
//                                startActivity(new Intent(PaymentActivity.this, MainActivity.class));
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call<DataResponse<PaymentsModels<List<VaNumberModels>>>> call, Throwable t) {
//
//                    }
//                });
//            }
//        });

    }

    public void savePaymentSuccess(){
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(ORDER_ID, "");
        if (editor.commit()){
            startActivity(new Intent(PaymentActivity.this, MainActivity.class));
            finish();
        }
    }
}

