package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.OrderHistoryAdapter;
import com.cygnusa.hyperm.autofit.AutofitTextView;
import com.cygnusa.hyperm.droppy.DroppyClickCallbackInterface;
import com.cygnusa.hyperm.droppy.DroppyMenuItem;
import com.cygnusa.hyperm.droppy.DroppyMenuPopup;
import com.cygnusa.hyperm.droppy.EasyDialog;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.OrderHistoryResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.Objects;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyWallet extends AppCompatActivity {
    TextView title, earnedPoints;
    Button purchaseNow;
    TransparentProgressDialog progressDialog;
    AutofitTextView points, unApprovedPoints;
    EmptyStateRecyclerView purchasedList;
    LinearLayoutManager linearLayoutManager;
    ProgressBar progressBar;
    ApiService restService;

    public OrderHistoryResponse dataOrderHistory = new OrderHistoryResponse();
    int TOTAL_RECORD = 0;
    int PAGE = 0;
    int LIMIT = 10;
    public static Handler.Callback callbackOrderHistory;
    public static String strCurrentAmount = "";

    ImageView rightMenu;
    EasyDialog easyDialog;
    DroppyMenuPopup droppyMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_wallet_history);
        rightMenu = findViewById(R.id.rightMenu);

        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        points = findViewById(R.id.points);
        unApprovedPoints = findViewById(R.id.unApprovedPoints);

        FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.getInstance(this);

        Bundle bundle = new Bundle();
       /* bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1");
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "MyWalletActivity");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
        // GlobalData.user.getData().setMpin("");
        purchaseNow = findViewById(R.id.btn_purchase);
        purchasedList = findViewById(R.id.redeemProductList);
        purchasedList.setHasFixedSize(true);
        purchasedList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(MyWallet.this);
        purchasedList.setLayoutManager(linearLayoutManager);
        purchasedList.addOnScrollListener(recyclerViewOnScrollListener);
        callbackOrderHistory = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getOrderHistory();
                return false;
            }
        };

        purchasedList.post(new Runnable() {
            @Override
            public void run() {

                getOrderHistory();
            }
        });


        purchasedList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));

        purchaseNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyWallet.this, RedeemProductListActivity.class));
            }
        });
        progressBar = findViewById(R.id.progressBar);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        initDroppyMenu();
        rightMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                easyDialog = new EasyDialog(MyWallet.this, droppyMenu)
                        .setLayout(droppyMenu.show())
                        .setGravity(EasyDialog.GRAVITY_BOTTOM)
                        .setBackgroundColor(Color.TRANSPARENT, Color.WHITE)
                        .setLocationByAttachedView(rightMenu)
                        .setAnimationTranslationShow(EasyDialog.DIRECTION_X, 350,
                                GlobalData.width, 0)
                        .setAnimationTranslationDismiss(EasyDialog.DIRECTION_X, 350, 0,
                                GlobalData.width).setTouchOutsideDismiss(true)
                        .setMatchParent(false).setMarginLeftAndRight(0, 15)
                        .setOutsideColor(Color.parseColor("#80000000")).show();

            }
        });
    }

    private void initDroppyMenu() {
        DroppyMenuPopup.Builder droppyBuilder = new DroppyMenuPopup.Builder(
                MyWallet.this, rightMenu);
        droppyBuilder.addMenuItem(new DroppyMenuItem("Change Pin", R.mipmap.icon_change_password))
                .triggerOnAnchorClick(false);
        droppyBuilder.setOnClick(new DroppyClickCallbackInterface() {
            @Override
            public void call(View v, int id) {
                easyDialog.dismiss();
                switch (id) {
                    case 0:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent i = new Intent(MyWallet.this, OtpActivity.class);
                                i.putExtra("type", "change");
                                startActivity(i);

                            }
                        }, 300);
                        break;
                }
            }
        });
        droppyMenu = droppyBuilder.build();
    }

    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

    private RecyclerView.OnScrollListener recyclerViewOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = linearLayoutManager.getChildCount();
            int totalItemCount = linearLayoutManager.getItemCount();
            int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();

            if (progressBar.getVisibility() != View.VISIBLE) {
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount < TOTAL_RECORD && dataOrderHistory.getData().size() < TOTAL_RECORD) {
                    PAGE++;
                    getOrderHistory();
                }
            }
        }
    };

    private void getOrderHistory() {
        if (new UtilService().isNetworkAvailable(this)) {
            progressDialog = new TransparentProgressDialog(this);
            progressDialog.show();
            try {
                restService.getOrderHistory(PAGE, LIMIT).enqueue(new Callback<OrderHistoryResponse>() {
                    @Override
                    public void onResponse(Call<OrderHistoryResponse> call, Response<OrderHistoryResponse> response) {
                        dataOrderHistory = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (dataOrderHistory != null && dataOrderHistory.getStatus() == 200) {
                            setDataOrderHistory();
                        } else if (response.body() != null && Objects.requireNonNull(response.body()).getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(HomeActivity.callback).sendEmptyMessage(0);
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(MyWallet.this, Objects.requireNonNull(response.body()).getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(Objects.requireNonNull(response.errorBody()).charStream(), ErrorResponse.class);
                            GlobalData.showToast(MyWallet.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OrderHistoryResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(MyWallet.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(MyWallet.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        finish();
        overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void setDataOrderHistory() {
        strCurrentAmount = dataOrderHistory.getCurrent_amount();
        if (dataOrderHistory != null) {
            int totalAmount = 0;
            try {
                totalAmount = Integer.parseInt(strCurrentAmount);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (totalAmount > 0) {
                purchaseNow.setEnabled(true);
                purchaseNow.setAlpha(1f);
            }
        }
        points.setText(dataOrderHistory.getCurrent_amount());
        if (dataOrderHistory.getUnapproved_amount() == null)
            unApprovedPoints.setText("0");
        else
            unApprovedPoints.setText("" + dataOrderHistory.getUnapproved_amount());
        OrderHistoryAdapter adapter = new OrderHistoryAdapter(this, dataOrderHistory.getData());
        purchasedList.setAdapter(adapter);

    }
}
