package com.cygnusa.hyperm.fragments;

import android.annotation.SuppressLint;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

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

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.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

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


public class LeaderBoardSalesFragment extends Fragment implements PositionUpdateListener {

    View mainView;
    ApiService restService;
    TrainingCategory category;
    EmptyStateRecyclerView leaderList;
    TextView positionOutof, name, location, duration, dateTime, position, score, dealerName, positionTop, positionOutofCount;
    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-MM-yyyy hh:mm a");

    ArrayList<String> MONTH_YEAR;
    int monthIndex = 0;
    Handler PICKER_HANDLER = new Handler();
    // LinearLayout linear1, linear2, linear3, ;
    CardView layout3;
    int isSales;
    public static int monthValue;
    LinearLayout layout2;
    public static int yearValue;
    public static Handler.Callback callback;

    public LeaderBoardSalesFragment() {

    }

    public void onResumeFragment() {

    }


    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_leaderboard_sales, 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);

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


        layout2 = mainView.findViewById(R.id.layout2);
        layout3 = mainView.findViewById(R.id.layout3);
        layout2.setVisibility(View.GONE);
        layout3.setVisibility(View.GONE);
        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);

        position = mainView.findViewById(R.id.position);
        score = mainView.findViewById(R.id.score);
        userImage = mainView.findViewById(R.id.userImage);
        cup = mainView.findViewById(R.id.cup);


        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) {
                getData(yearValue, monthValue);
                return false;
            }
        };

    }

    public void getData(int yearValue, int monthValue) {
        if (isSales == 0) {
            getLeaderBoardListByCategory(isSales, "", yearValue, monthValue);
        } else if (isSales == 1) {
            getLeaderBoardListByCategory(isSales, "region", yearValue, monthValue);
        } else if (isSales == 2) {
            getLeaderBoardListByCategory(isSales, "zone", yearValue, monthValue);
        } else if (isSales == 3) {
            getLeaderBoardListByCategory(isSales, "panindia", yearValue, monthValue);
        }
    }

    public void setIsSales(int isSales) {
        this.isSales = isSales;
    }

    public void splitMonth(String myear) {
        String[] str = myear.trim().split(" ");
        String month = str[0];
        String year = str[1];
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            Date date = dateFormat.parse("01-" + month + "-" + year);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int monthValue = calendar.get(Calendar.MONTH) + 1;
            int yearValue = calendar.get(Calendar.YEAR);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @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) {
            MONTH_YEAR = generateMonthAndYear(10);
            monthIndex = MONTH_YEAR.size() - 1;
            Calendar calendar = Calendar.getInstance();

            if (isSales == 0) {
                getLeaderBoardListByCategory(isSales, "", yearValue, monthValue);
            } else if (isSales == 1) {
                getLeaderBoardListByCategory(isSales, "region", yearValue, monthValue);
            } else if (isSales == 2) {
                getLeaderBoardListByCategory(isSales, "zone", yearValue, monthValue);
            } else if (isSales == 3) {
                getLeaderBoardListByCategory(isSales, "panindia", yearValue, monthValue);
            }

        }
    }

    private void getLeaderBoardListByCategory(int isSales, String type, int year, int month) {

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

            try {
                if (isSales == 0) {
                    restService.getLeaderBoardList(String.valueOf(year), String.valueOf(month))
                            .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) {

                                        layout2.setVisibility(View.VISIBLE);
                                        layout3.setVisibility(View.VISIBLE);
                                        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.getLeaderBoardSalesTypeList(type, String.valueOf(year), String.valueOf(month))
                            .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) {

                                        layout2.setVisibility(View.VISIBLE);
                                        layout3.setVisibility(View.VISIBLE);
                                        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 ArrayList<String> generateMonthAndYear(int last) {
        ArrayList<String> yearList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat format1 = new SimpleDateFormat("MMM yyyy");

        for (int i = currentYear; i > currentYear - last; i--) {
            if (i == currentYear) {
                for (int j = currentMonth; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                for (int j = 12; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return yearList;
    }


    @SuppressLint("SetTextI18n")
    private void setLeaderBoard(String total) {
        positionOutof.setText(String.format("%s Out of %s", LEADER_BOARD.getRank(), total));
        positionTop.setText(String.format("Top %s", LEADER_BOARD_LIST.size()));
        positionOutofCount.setText(String.format("Out of %s", total));
        name.setText(String.format("%s %s", 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 ? d + "%" : d + "%");
            } catch (Exception e) {
                e.printStackTrace();
            }

            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();
            }

        }

        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, LeaderBoardSalesFragment.this);
        leaderList.setAdapter(adapter);
    }


    @Override
    public void onPositionUpdate(int position) {

        LAST_CLICKED_POSITION = position;

    }


}
