package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
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 android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.cygnusa.hyperm.autofit.AutofitTextView;
import com.cygnusa.hyperm.fragments.RewardPointFragment;
import com.cygnusa.hyperm.screenpinview.AppLockActivity;
import com.cygnusa.hyperm.tooltip.Tooltip;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
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.FragmentItem;
import com.cygnusa.hyperm.wrappers.LearningLevel;
import com.cygnusa.hyperm.wrappers.LevelData;
import com.cygnusa.hyperm.wrappers.RedeemToWalletResponse;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

import java.util.ArrayList;

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

public class MyEarnedPoints extends AppCompatActivity {
    TextView title, earnedPoints, text_rules;
    Button btnRedeemNow;
    TransparentProgressDialog progressDialog;
    ViewPager earningPager;
    SmartTabLayout earningTab;
    ArrayList<String> arrEarnedPoints = new ArrayList<>();
    ArrayList<FragmentItem> fragments = new ArrayList<>();
    EarningPointsAdapter adapter;
    AutofitTextView points;
    public static Handler.Callback myEarnedPointsCallback;
    ApiService restService;
    public String currPoint = "";
    public RedeemToWalletResponse data = new RedeemToWalletResponse();
    int cPoints;
    private TextView minPoint;
    public LearningLevel responseLevel = new LearningLevel();
    public ArrayList<LevelData> LEARNING_LEVEL_LIST = new ArrayList<>();
    View mView;

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

        setContentView(R.layout.activity_earned_points);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        minPoint = findViewById(R.id.text_message);
        text_rules = findViewById(R.id.text_rules);
        points = findViewById(R.id.points);
        earnedPoints = findViewById(R.id.earned);
        btnRedeemNow = findViewById(R.id.btn_redeem);
        earningPager = findViewById(R.id.myEarningPager);
        earningTab = findViewById(R.id.myEarningPagerTab);
        arrEarnedPoints.clear();
        arrEarnedPoints.add("Earned History");
        arrEarnedPoints.add("Redeem History");

        text_rules.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRulesPopup();
            }
        });

        btnRedeemNow.setEnabled(false);
        btnRedeemNow.setAlpha(0.3f);
        setLeaderBoardCategory();
        earningPager.setOffscreenPageLimit(0);
        btnRedeemNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int cPoints = Integer.parseInt(currPoint);
                new androidx.appcompat.app.AlertDialog.Builder(MyEarnedPoints.this)
                        .setMessage("Confirm redemption of points to your wallet?")
                        .setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        getRedeemNow();
                                    }
                                }).setNegativeButton("Cancel", null).show();


            }
        });
        earningPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {
            }

            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
                try {
                    RewardPointFragment fragment = (RewardPointFragment) fragments.get(position).getFragment();

//                    if (position == 0) {
//                        earnedPoints.setText(String.format("Total Points Earned %s", fragment.getTotalPoint()));
//                    } else {
//                        earnedPoints.setText(String.format("Total Points Redeemed %s", fragment.getTotalPoint()));
//                    }

                    if (position == 0) {
//                    earnedPoints.setText(String.format("Total Points Earned %s", fragment.getTotalPoint()));
                        earnedPoints.setText(String.format("Total Points Earned %s", "1000"));
                    } else {
//                    earnedPoints.setText(String.format("Total Points Redeemed %s", fragment.getTotalPoint()));
                        earnedPoints.setText(String.format("Total Points Redeemed %s", "500"));
                    }


                    currPoint = fragment.getCurrentPoint();
                    cPoints = Integer.parseInt(currPoint);
                    points.setText(fragment.getCurrentPoint() + "");
                    minPoint.setText(String.format("Minimum  %s points required for redemption", fragment.getMinPoint()));
                    if (fragment.getIs_Redeem_Point().equalsIgnoreCase("0") || cPoints == 0) {
                        btnRedeemNow.setEnabled(false);
                        btnRedeemNow.setAlpha(0.3f);
                    } else if (fragment.getIs_Redeem_Point().equalsIgnoreCase("1") || cPoints >= 1500) {
                        btnRedeemNow.setEnabled(true);
                        btnRedeemNow.setAlpha(1f);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        myEarnedPointsCallback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                RewardPointFragment fragment = (RewardPointFragment) fragments.get(earningPager.getCurrentItem()).getFragment();
                if (earningPager.getCurrentItem() == 0) {
//                    earnedPoints.setText(String.format("Total Points Earned %s", fragment.getTotalPoint()));
                    earnedPoints.setText(String.format("Total Points Earned %s", "1000"));
                } else {
//                    earnedPoints.setText(String.format("Total Points Redeemed %s", fragment.getTotalPoint()));
                    earnedPoints.setText(String.format("Total Points Redeemed %s", "500"));
                }
//                currPoint = fragment.getCurrentPoint();
//                cPoints = Integer.parseInt(currPoint);
//                points.setText(fragment.getCurrentPoint());
//                minPoint.setText(String.format("Minimum  %s points required for redemption", fragment.getMinPoint()));
//                if (fragment.getIs_Redeem_Point().equalsIgnoreCase("0") || cPoints == 0) {
//                    btnRedeemNow.setEnabled(false);
//                    btnRedeemNow.setAlpha(0.3f);
//                } else if (fragment.getIs_Redeem_Point().equalsIgnoreCase("1") || cPoints >= 1500) {
//                    btnRedeemNow.setEnabled(true);
//                    btnRedeemNow.setAlpha(1f);
//                }
                btnRedeemNow.setEnabled(true);
                btnRedeemNow.setAlpha(1f);

                return false;
            }
        };

        findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        getLearningData();
        findViewById(R.id.info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setupView();
                Tooltip.TooltipView tooltip = Tooltip.make(MyEarnedPoints.this,
                        new Tooltip.Builder(101)
                                .anchor(view, Tooltip.Gravity.BOTTOM)
                                .closePolicy(new Tooltip.ClosePolicy()
                                        .insidePolicy(true, false)
                                        .outsidePolicy(true, false), 0)
                                .activateDelay(800)
                                .withStyleId(R.style.ToolTipLayoutCustomStyle)
                                .showDelay(300)
                                .text("")
                                .setBgColor(getResources().getColor(R.color.white))
                                .view(mView)
                                .maxWidth(800)
                                .withArrow(true)
                                .build()
                );
                tooltip.setTextColor(Color.YELLOW);
                tooltip.show();
            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        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);
    }

    private void openRulesPopup() {

        final Dialog aDialog = new Dialog(this);
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_reward_rules);
        aDialog.setCancelable(true);
        ImageView img_close = aDialog.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aDialog.dismiss();
            }
        });
        aDialog.show();

    }


    private void getLearningData() {
        if (new UtilService().isNetworkAvailable(this)) {
            progressDialog = new TransparentProgressDialog(this);
            progressDialog.show();
            try {
                restService.getLearninglevel()
                        .enqueue(new Callback<LearningLevel>() {
                            @Override
                            public void onResponse(Call<LearningLevel> call, Response<LearningLevel> response) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                if (response.body() != null && response.body().getStatus() == 200) {
                                    responseLevel = response.body();
                                    LEARNING_LEVEL_LIST = response.body().getData();
                                } else if (response.body() != null && response.body().getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                    finish();
                                } else if (response.body() != null) {
                                    GlobalData.showToast(MyEarnedPoints.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                } else if (response.errorBody() != null) {
                                    Gson gson = new Gson();
                                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                    GlobalData.showToast(MyEarnedPoints.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<LearningLevel> call, Throwable t) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                GlobalData.showToast(MyEarnedPoints.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                            }
                        });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                GlobalData.showToast(MyEarnedPoints.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
        } else {
            GlobalData.showToast(MyEarnedPoints.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }


    private void setupView() {
        mView = LayoutInflater.from(MyEarnedPoints.this).inflate(R.layout.tooltip, null);
        LinearLayout vocItemExpLayout = (LinearLayout) mView.findViewById(R.id.linearLevel);
        vocItemExpLayout.removeAllViews();
        for (int i = 0; i < LEARNING_LEVEL_LIST.size(); i++) {
            View view = LayoutInflater.from(this).inflate(
                    R.layout.tooltip_item, null);
            TextView levelText = (TextView) view.findViewById(R.id.level);
            TextView levelPointText = (TextView) view.findViewById(R.id.level_point);
            TextView levelRateText = (TextView) view.findViewById(R.id.level_rate);
            levelText.setText(LEARNING_LEVEL_LIST.get(i).getLvl_name());
            levelPointText.setText("1");
            levelRateText.setText(LEARNING_LEVEL_LIST.get(i).getLvl_points());
            vocItemExpLayout.addView(view);
        }


    }


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

                        if (data != null && data.getStatus() == 200) {
                            if (GlobalData.user.getData().getMpin().trim().isEmpty()) {
                                Intent i = new Intent(MyEarnedPoints.this, OtpActivity.class);
                                i.putExtra("type", "redeem");
                                startActivity(i);
                                finish();
                            } else {
                                startActivity(new Intent(MyEarnedPoints.this, AppLockActivity.class));
                                finish();
                            }

                        } else if (GlobalData.user != null) {
                            GlobalData.showToast(MyEarnedPoints.this, GlobalData.user.getMessage(), Toast.LENGTH_SHORT).show();

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

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

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

    }

    public void showView() {

    }


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

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

    public class EarningPointsAdapter extends FragmentStatePagerAdapter {

        ArrayList<String> categories;


        private EarningPointsAdapter(FragmentManager fm, ArrayList<String> list) {
            super(fm);
            categories = list;
            fragments = new ArrayList<>();
        }

        @Override
        public Fragment getItem(int position) {

            RewardPointFragment fragment = new RewardPointFragment();
            fragment.setIsEarnedHistory(position == 0);
            FragmentItem item = new FragmentItem();
            item.setFragment(fragment);
            item.setTitle(categories.get(position));
            fragments.add(item);
            return fragment;
        }

        @Override
        public int getCount() {
            return categories.size();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return categories.get(position);
        }
    }

    private void setLeaderBoardCategory() {
        earningPager.setPageTransformer(true, new DepthPageTransformerNew());
        adapter = new EarningPointsAdapter(getSupportFragmentManager(),
                arrEarnedPoints);
        earningPager.setAdapter(adapter);
        earningTab.setViewPager(earningPager);
    }


    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }
}
