package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.adapter.LeaderBoardListAdapter;
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.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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

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

public class LeaderBoardListFragment extends Fragment implements PositionUpdateListener {

    View mainView;
    ApiService restService;
    TrainingCategory category;
    EmptyStateRecyclerView leaderList;
    TextView positionOutof, name, location, duration, dateTime, position, score, positionTop,positionOutofCount, dealerName,positionName;
    ImageView userImage, cup;
    int LAST_CLICKED_POSITION = -1;
    String TRAINING_ID = "";
    LeaderBoardListAdapter adapter;
    TransparentProgressDialog progressDialog;
    ArrayList<LeaderBoard> LEADER_BOARD_LIST = new ArrayList<>();
    UserData LEADER_BOARD = new UserData();
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
    CardView leaderBoardList;
    ArrayList<String> MONTH_YEAR;

    Handler PICKER_HANDLER = new Handler();
    int isAssessment;
    LinearLayout linear1,linear2,linear3;

    public LeaderBoardListFragment() {

    }

    public void onResumeFragment() {

    }

    public void setIsAssessment(int isAssessment) {
        this.isAssessment = isAssessment;
    }

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

    public void setTrainingId(String id) {
        this.TRAINING_ID = id;
    }

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        leaderList = mainView.findViewById(R.id.leaderList);
        leaderBoardList =mainView.findViewById(R.id.list_leaderbord);
        positionOutof = mainView.findViewById(R.id.positionOutof);
        positionName = mainView.findViewById(R.id.pos_text);
        name = mainView.findViewById(R.id.name);
        location = mainView.findViewById(R.id.location);
        duration = mainView.findViewById(R.id.duration);
        dealerName = mainView.findViewById(R.id.dealer_name);
        dateTime = mainView.findViewById(R.id.dateTime);

        positionTop = mainView.findViewById(R.id.topcount);
        positionOutofCount = mainView.findViewById(R.id.outofcount);

        position = mainView.findViewById(R.id.position);
        score = mainView.findViewById(R.id.score);
        userImage = mainView.findViewById(R.id.userImage);
        cup = mainView.findViewById(R.id.cup);
        linear1 = mainView.findViewById(R.id.linear1);
        linear2 = mainView.findViewById(R.id.linear2);
        linear3 = mainView.findViewById(R.id.linear3);
        leaderBoardList.setVisibility(View.GONE);
        linear1.setVisibility(View.GONE);
        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();


    }


    @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) {

            if (isAssessment == 0) {
                getAssessmentLeaderBoard(isAssessment, "");
            } else if (isAssessment == 1) {
                getAssessmentLeaderBoard(isAssessment, "region");
            } else if (isAssessment == 2) {
                getAssessmentLeaderBoard(isAssessment, "zone");
            }else if (isAssessment == 3) {
                getAssessmentLeaderBoard(isAssessment, "panindia");
            }


        }
    }

    private void getAssessmentLeaderBoard(int isAssessment, String type) {

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

            try {

                if (isAssessment == 0) {
                    restService.getLeaderBoardAssessmentList()
                            .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(response.body().getTotal());
                                    } 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<LeaderBoardResponse> call, Throwable t) {
                                    if (progressDialog != null && progressDialog.isShowing()) {
                                        progressDialog.dismiss();
                                    }
                                    GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                                }
                            });

                } else {
                    restService.getLeaderBoardAssessmentTypeList(type)
                            .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(response.body().getTotal());
                                    } 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<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(String total) {
        leaderBoardList.setVisibility(View.VISIBLE);
        linear1.setVisibility(View.VISIBLE);
        positionOutof.setText(String.format("%s Out of %s", LEADER_BOARD.getRank(), total));
        positionTop.setText(String.format("Top %s", total));
        positionOutofCount.setText(String.format("Out of %s", total));
        name.setText(LEADER_BOARD.getUser().getFname() + " " + LEADER_BOARD.getUser().getLname());
        location.setText(LEADER_BOARD.getUser().getDealer().getCity());
        dealerName.setText(LEADER_BOARD.getUser().getDealer().getDealer_name());
        position.setText(LEADER_BOARD.getRank());
        if (LEADER_BOARD.getRank().isEmpty()) {
            cup.setVisibility(View.GONE);
            duration.setText("Assessment not done");
            dateTime.setText("");
        } else {
            cup.setVisibility(View.VISIBLE);
            try {
                int d = (int) Math.round(Double.parseDouble(LEADER_BOARD.getPercentage().trim()));
                score.setText(String.valueOf(d).length() > 1 ? String.valueOf(d) + "%" : String.valueOf(d) + "%");
            } catch (Exception e) {

            }
            try {
                dateTime.setText("Completed on: " + format1.format(format.parse(LEADER_BOARD.getLast_time())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                long millis = Long.valueOf(LEADER_BOARD.getTotal_time()) * 1000;
                String formattedTime = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                        TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
                        TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
                duration.setText("Total Duration: " + formattedTime);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if(total.equalsIgnoreCase("0") && total!=null){
            linear1.setVisibility(View.GONE);
            linear2.setVisibility(View.GONE);
            linear3.setVisibility(View.GONE);
        }

        Glide.with(this).load(LEADER_BOARD.getUser().getProfile_photo())
                .thumbnail(Glide.with(this).load(R.drawable.gif_loader))
                .into(userImage);
        adapter = new LeaderBoardListAdapter(getActivity(), LEADER_BOARD_LIST, LeaderBoardListFragment.this);
        leaderList.setAdapter(adapter);
    }


    @Override
    public void onPositionUpdate(int position) {

        LAST_CLICKED_POSITION = position;

    }


}
