package com.cygnusa.hyperm.fragments;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.MyEarnedPoints;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.adapter.RedeemPointsAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.PositionUpdateListener;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.RewardPoints;
import com.cygnusa.hyperm.wrappers.RewardPointsResponse;
import com.google.gson.Gson;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.ArrayList;

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


public class RewardPointFragment extends Fragment implements PositionUpdateListener {

    View mainView;
    ApiService restService;
    EmptyStateRecyclerView rewardPointsList;
    int LAST_CLICKED_POSITION = -1;
    RedeemPointsAdapter adapter;
    TransparentProgressDialog progressDialog;
    RewardPointsResponse REWARD_POINT = new RewardPointsResponse();
    ArrayList<RewardPoints> REWARD_POINTS_LIST = new ArrayList<>();
    LinearLayoutManager linearLayoutManager;
    int TOTAL_RECORD = 0;
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    int PAGE = 0;
    int LIMIT = 10;
    ProgressBar progressBar;

    boolean isEarnedHistory;

    public RewardPointFragment() {

    }

    public void onResumeFragment() {

    }

    public void setIsEarnedHistory(boolean isEarnedHistory) {
        this.isEarnedHistory = isEarnedHistory;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_reward_points, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        rewardPointsList = mainView.findViewById(R.id.rewardpoints);
        rewardPointsList.setHasFixedSize(true);
        rewardPointsList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rewardPointsList.setLayoutManager(linearLayoutManager);
        rewardPointsList.addOnScrollListener(recyclerViewOnScrollListener);
        progressBar = mainView.findViewById(R.id.progressBar);
        rewardPointsList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(getActivity(), "No data available", ""));
        mViewCreated = true;
        // getRewardPointHistory();
        onViewCreatedFirstSight();
    }

    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 && REWARD_POINTS_LIST.size() < TOTAL_RECORD) {
                    PAGE++;
                    // getRewardPointHistory();
                }
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewCreated = false;
        mUserSeen = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!mUserSeen && isVisibleToUser) {
            mUserSeen = true;
            onViewCreatedFirstSight();
        }
    }


    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {

        if (mUserSeen && mViewCreated) {
            //getRewardPointHistory();
            setRewardPoints(isEarnedHistory);
        }
    }

    private void getRewardPointHistory() {
        if (new UtilService().isNetworkAvailable(getActivity())) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                restService.getRewardPointHistory(isEarnedHistory ? "rewardpoints" : "redeemhistory", PAGE, LIMIT)
                        .enqueue(new Callback<RewardPointsResponse>() {
                            @Override
                            public void onResponse(Call<RewardPointsResponse> call, Response<RewardPointsResponse> response) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }

                                if (response.body() != null && response.body().getStatus() == 200) {
                                    REWARD_POINTS_LIST = response.body().getData();
                                    REWARD_POINT = response.body();
                                    if (REWARD_POINTS_LIST == null) {
                                        REWARD_POINTS_LIST = new ArrayList<>();
                                    }
                                    if (REWARD_POINTS_LIST.size() == 0) {
                                        rewardPointsList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                                    } else {
                                        rewardPointsList.invokeState(EmptyStateRecyclerView.STATE_OK);
                                    }
                                    setRewardPoints(isEarnedHistory);
                                } 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(getActivity(), 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(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                                    if (message.getStatus() == 401) {
                                        GlobalData.canLogout = true;
                                        new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                    }
                                }
                            }

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

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

    private void setRewardPoints(boolean isEarnedHistory) {

        adapter = new RedeemPointsAdapter(getActivity(), REWARD_POINTS_LIST, RewardPointFragment.this, isEarnedHistory);
        rewardPointsList.setAdapter(adapter);
        new Handler(MyEarnedPoints.myEarnedPointsCallback).sendEmptyMessage(0);
    }


    @Override
    public void onPositionUpdate(int position) {
        LAST_CLICKED_POSITION = position;
    }


    public String getTotalPoint() {
        return REWARD_POINT.getTotal_point();
    }

    public String getMinPoint() {
        return REWARD_POINT.getMin_redeem_point();
    }

    public String getCurrentPoint() {
        return REWARD_POINT.getCurrent_point();
    }

    public String getIs_Redeem_Point() {
        return REWARD_POINT.getIs_redeem_point();
    }
}
