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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
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.AMHomeActivity;
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.cygnusa.hyperm.wrappers.ZoneResponse;
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 TRDSEFragment 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;
    private LinearLayout linearRegion;
    private LinearLayout linearArea;
    private Spinner spinZone, spinRegion, spinArea;
    private ArrayList<String> regionList;
    private ArrayList<String> zoneList;
    private ArrayList<String> areaList;

    private ZoneResponse RM_DATA = new ZoneResponse();
    private ZoneResponse ZM_DATA = new ZoneResponse();
    private ZoneResponse AM_DATA = new ZoneResponse();
    private String RM_MAIL = "";
    private String ZM_MAIL = "";
    private String AM_MAIL = "";

    public TRDSEFragment() {

    }

    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_dse_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", ""));

        linearRegion = mainView.findViewById(R.id.LinearRegion);
        LinearLayout linearZone = mainView.findViewById(R.id.LinearZone);
        spinZone = mainView.findViewById(R.id.spinZone);
        linearArea = mainView.findViewById(R.id.LinearArea);

        spinRegion = mainView.findViewById(R.id.spinRegion);
        spinArea = mainView.findViewById(R.id.spinArea);
        regionList = new ArrayList<>();
        zoneList = new ArrayList<>();
        areaList = new ArrayList<>();

        linearArea.setVisibility(View.GONE);
        linearRegion.setVisibility(View.GONE);
        linearZone.setVisibility(View.GONE);

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
            linearRegion.setVisibility(View.VISIBLE);
            linearArea.setVisibility(View.VISIBLE);
        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
            linearArea.setVisibility(View.VISIBLE);
        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
            linearZone.setVisibility(View.VISIBLE);
            linearRegion.setVisibility(View.VISIBLE);
            linearArea.setVisibility(View.VISIBLE);
        }

        mViewCreated = true;
        onViewCreatedFirstSight();

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (!ZM_MAIL.isEmpty() && !RM_MAIL.isEmpty() && !AM_MAIL.isEmpty()) {
                    getLeaderBoard(ZM_MAIL, RM_MAIL, AM_MAIL);
                } else {
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getZMDetails();
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                        getRMDetails(GlobalData.user.getData().getEmailid(), GlobalData.user.getData().getZone());
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
                        getAMDetails(GlobalData.user.getData().getEmailid());
                    } else {
                        getLeaderBoard("all", "all", GlobalData.user.getData().getEmailid());
                    }
                }
                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();
        }
    }

    private void getZMDetails() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                restService.getZone().enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        ZM_DATA = response.body();

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (ZM_DATA != null && ZM_DATA.getStatus() == 200) {
                            zoneList.clear();
                            zoneList.add("All");
                            for (int i = 0; i < ZM_DATA.getData().size(); i++) {
                                zoneList.add(ZM_DATA.getData().get(i).getName());
                            }
                            setZMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.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(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                Log.e("iop", e.toString() + "");

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setZMDetails() {
        if (zoneList == null || zoneList.size() == 0) {
            return;
        }

        ArrayAdapter<String> zoneAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, zoneList);
        zoneAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinZone.setAdapter(zoneAdapter);

        spinZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    linearRegion.setVisibility(View.GONE);
                    linearArea.setVisibility(View.GONE);
                    getLeaderBoard("all", "all", "all");
                } else {
                    linearRegion.setVisibility(View.VISIBLE);
                    String email = ZM_DATA.getData().get(i - 1).getEmail();
                    String zone = ZM_DATA.getData().get(i - 1).getZone();
                    getRMDetails(email, zone);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinZone.setSelection(0);
    }

    private void getRMDetails(String email, String zone) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("zone", email);
                map.put("zonename", zone);
                restService.getRegion(map).enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        RM_DATA = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (RM_DATA != null && RM_DATA.getStatus() == 200) {
                            regionList.clear();
                            regionList.add("All");
                            for (int i = 0; i < RM_DATA.getData().size(); i++) {
                                regionList.add(RM_DATA.getData().get(i).getName());
                            }
                            setRMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.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(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setRMDetails() {
        if (regionList == null || regionList.size() == 0) {
            return;
        }

        ArrayAdapter<String> regionAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, regionList);
        regionAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinRegion.setAdapter(regionAdapter);

        spinRegion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    linearArea.setVisibility(View.GONE);
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getLeaderBoard(ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                "all", "all");
                    } else {
                        getLeaderBoard(GlobalData.user.getData().getEmailid(), "all", "all");
                    }
                } else {
                    linearArea.setVisibility(View.VISIBLE);
                    String email = RM_DATA.getData().get(i - 1).getEmail();
                    getAMDetails(email);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinRegion.setSelection(0);
    }

    private void getAMDetails(String email) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(getActivity()))) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("region", email);
                restService.getArea(map).enqueue(new Callback<ZoneResponse>() {
                    @Override
                    public void onResponse(Call<ZoneResponse> call, Response<ZoneResponse> response) {
                        AM_DATA = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (AM_DATA != null && AM_DATA.getStatus() == 200) {
                            setAMDetails();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(AMHomeActivity.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(AMHomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ZoneResponse> call, Throwable t) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }

    }

    private void setAMDetails() {
        areaList.clear();
        areaList.add("All");
        for (int i = 0; i < AM_DATA.getData().size(); i++) {
            areaList.add(AM_DATA.getData().get(i).getName());
        }

        if (areaList == null || areaList.size() == 0) {
            return;
        }

        ArrayAdapter<String> areaAdapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
                R.layout.spinner_region, areaList);
        areaAdapter.setDropDownViewResource(R.layout.spinner_region);
        spinArea.setAdapter(areaAdapter);

        spinArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getLeaderBoard(ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                "all");
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                        getLeaderBoard("",
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                "all");
                    } else {
                        getLeaderBoard("", GlobalData.user.getData().getEmailid(), "all");
                    }
                } else {
                    String email = AM_DATA.getData().get(i - 1).getEmail();
                    if (GlobalData.user.getData().getRole().equalsIgnoreCase("3")) {
                        getLeaderBoard(ZM_DATA.getData().get(spinZone.getSelectedItemPosition() - 1).getEmail(),
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                email);
                    } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                            || GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
                        getLeaderBoard("",
                                RM_DATA.getData().get(spinRegion.getSelectedItemPosition() - 1).getEmail(),
                                email);
                    } else {
                        getLeaderBoard("", GlobalData.user.getData().getEmailid(), email);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spinArea.setSelection(0);
    }


    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {
//        if (mUserSeen && mViewCreated) {
//
//        }
    }

    private void getLeaderBoard(String zmemail, String rmemail, String amemail) {

        ZM_MAIL = zmemail;
        RM_MAIL = rmemail;
        AM_MAIL = amemail;

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
            amemail = "all";
            rmemail = "all";
            zmemail = "all";
            AM_MAIL = "all";
            RM_MAIL = "all";
            ZM_MAIL = "all";
        }

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("5")) {
            zmemail = "all";
            ZM_MAIL = "all";
        }

        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", "DSE");
                map.put("zmemail", zmemail);
                map.put("rmemail", rmemail);
                map.put("amemail", amemail);
                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);
    }

}
