package com.cygnusa.hyperm.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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

import com.google.gson.Gson;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.LoginActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.adapter.TRLeaderBoardAdapter;
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.LeaderBoard;
import com.cygnusa.hyperm.wrappers.LeaderBoardResponse;
import com.cygnusa.hyperm.wrappers.TrainingCategory;
import com.cygnusa.hyperm.wrappers.UserData;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

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


public class TRZonalFragment extends Fragment {

    public static Handler.Callback callback;
    View mainView;
    ApiService restService;
    TrainingCategory category;
    TRLeaderBoardAdapter adapter;
    TransparentProgressDialog progressDialog;
    private EmptyStateRecyclerView leaderList;
    private ArrayList<LeaderBoard> LEADER_BOARD_LIST = new ArrayList<>();
    private UserData LEADER_BOARD = new UserData();
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;

    public TRZonalFragment() {

    }

    public void onResumeFragment() {

    }


    public void setCategory(TrainingCategory trainingCategory) {
        this.category = trainingCategory;
    }

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) Objects.requireNonNull(getActivity()).getApplication()).getClient();
        leaderList = mainView.findViewById(R.id.leaderList);

        leaderList.setHasFixedSize(true);
        leaderList.setItemAnimator(new SlideInLeftAnimator());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        leaderList.setLayoutManager(linearLayoutManager);
        leaderList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(getActivity(), "No data available", ""));
        mViewCreated = true;
        onViewCreatedFirstSight();

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getLeaderBoard();
                return false;
            }
        };

    }

    @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) {
//            getLeaderBoard();
//        }
    }

    private void getLeaderBoard() {

        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();

            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("month", String.valueOf(TeamRankingSalesFragment.monthValue));
                map.put("year", String.valueOf(TeamRankingSalesFragment.yearValue));
                map.put("role", "ZM");
                map.put("location", "P");
                restService.getTeamLeaderBoardMySales(map)
                        .enqueue(new Callback<LeaderBoardResponse>() {
                            @Override
                            public void onResponse(Call<LeaderBoardResponse> call, Response<LeaderBoardResponse> response) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                if (response.body() != null && response.body().getStatus() == 200) {
                                    LEADER_BOARD_LIST = response.body().getData();
                                    LEADER_BOARD = response.body().getUser_data();
                                    if (LEADER_BOARD_LIST == null) {
                                        LEADER_BOARD_LIST = new ArrayList<>();
                                    }
                                    if (LEADER_BOARD == null) {
                                        LEADER_BOARD = new UserData();
                                    }
                                    if (LEADER_BOARD_LIST.size() == 0) {
                                        leaderList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                                    } else {
                                        leaderList.invokeState(EmptyStateRecyclerView.STATE_OK);
                                    }
                                    setLeaderBoard();
                                } 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;
                                        GlobalData.zmEmail = "none";
                                        GlobalData.rmEmail = "none";
                                        GlobalData.amEmail = "none";
                                        startActivity(new Intent(getActivity(), LoginActivity.class));
                                        Objects.requireNonNull(getActivity()).finish();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<LeaderBoardResponse> 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 setLeaderBoard() {
        adapter = new TRLeaderBoardAdapter(getActivity(), LEADER_BOARD_LIST);
        leaderList.setAdapter(adapter);
    }

}
