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.ImageButton;
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.LoginActivity;
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.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.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

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

public class AMLeaderBoardListFragment extends Fragment implements PositionUpdateListener {

    public static Handler.Callback callback;
    private String iMonthValue;
    View mainView;
    ApiService restService;
    EmptyStateRecyclerView leaderList;
    private String iYearValue;
    private TextView positionOutof, name, location, duration, dateTime, position,
            score, positionTop, positionOutofCount, dealerName;
    LeaderBoardListAdapter adapter;
    TransparentProgressDialog progressDialog;
    ArrayList<LeaderBoard> LEADER_BOARD_LIST = new ArrayList<>();
    UserData LEADER_BOARD = new UserData();
    private ImageView userImage, cup;
    ArrayList<String> MONTH_YEAR;
    private CardView leaderBoardList;
    boolean isVisible = false;
    LinearLayoutManager linearLayoutManager;
    private LinearLayout linear1, linear2, linear3;
    private int monthIndex = 0;
    private boolean mUserSeen = false;
    private boolean mViewCreated = true;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
    private ImageButton previous, next;
    private TextView monthText;

    public AMLeaderBoardListFragment() {

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_leader_board_am, 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);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        leaderBoardList = mainView.findViewById(R.id.list_leaderbord);
        positionOutof = mainView.findViewById(R.id.positionOutof);
        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();

        previous = mainView.findViewById(R.id.previous);
        next = mainView.findViewById(R.id.next);
        monthText = mainView.findViewById(R.id.MonthText);
        next.setEnabled(false);

        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                monthIndex = monthIndex - 1;
                next.setEnabled(true);
                monthText.setText(MONTH_YEAR.get(monthIndex));
                splitMonth(MONTH_YEAR.get(monthIndex));
                if (monthIndex == 0) {
                    previous.setEnabled(false);
                }

            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                monthIndex = monthIndex + 1;
                previous.setEnabled(true);
                monthText.setText(MONTH_YEAR.get(monthIndex));
                splitMonth(MONTH_YEAR.get(monthIndex));
                if (monthIndex == MONTH_YEAR.size() - 1) {
                    next.setEnabled(false);
                }
            }
        });

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (iMonthValue == null && iYearValue == null) {
                    MONTH_YEAR = generateMonthAndYear();
                    monthIndex = MONTH_YEAR.size() - 1;
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;
                    iYearValue = String.valueOf(year);
                    iMonthValue = String.valueOf(month);
                }
                monthText.setText(MONTH_YEAR.get(MONTH_YEAR.size() - 1));
                getLeaderBoard(iMonthValue, iYearValue);
                return false;
            }
        };

    }

    private 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);
            iMonthValue = String.valueOf(calendar.get(Calendar.MONTH) + 1);
            iYearValue = String.valueOf(calendar.get(Calendar.YEAR));
            getLeaderBoard(iMonthValue, iYearValue);
        } 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) {
//
//        }
    }

    private void getLeaderBoard(String month, String year) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("month", month);
                map.put("year", year);
                map.put("location", "P");

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

            }
        } else {
            GlobalData.showToast(getActivity(), "No internet connection", Toast.LENGTH_LONG).show();
        }
    }

    @SuppressLint("SetTextI18n")
    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));
        if (LEADER_BOARD_LIST != null && LEADER_BOARD_LIST.size() > 0) {
            positionTop.setText(String.format("Top %s", LEADER_BOARD_LIST.size()));
        }
        if (LEADER_BOARD.getTotal_time() == null || LEADER_BOARD.getTotal_time().equalsIgnoreCase(""))
            duration.setVisibility(View.GONE);
        else {
            duration.setVisibility(View.VISIBLE);
        }
        if (LEADER_BOARD.getUser().getCity() == null || LEADER_BOARD.getUser().getCity().equalsIgnoreCase(""))
            location.setVisibility(View.GONE);
        else {
            location.setVisibility(View.VISIBLE);
        }

        if (LEADER_BOARD.getUser().getDealer().getDealer_name() == null || LEADER_BOARD.getUser().getDealer().getDealer_name().equalsIgnoreCase(""))
            dealerName.setVisibility(View.GONE);
        else {
            dealerName.setVisibility(View.VISIBLE);
        }
        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();
            }
        }
        if (total != null && total.equalsIgnoreCase("0")) {
            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, AMLeaderBoardListFragment.this);
        leaderList.setAdapter(adapter);
    }

    private ArrayList<String> generateMonthAndYear() {
        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 - 10; 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;
    }

    @Override
    public void onPositionUpdate(int position) {
    }


}
