package com.cygnusa.hyperm.fragments;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
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.R;
import com.cygnusa.hyperm.adapter.SurveyAdapter;
import com.cygnusa.hyperm.fancyshowcase.DismissListener;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.PositionUpdateListener;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.Survey;
import com.cygnusa.hyperm.wrappers.SurveyResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

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

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

public class SurveyFragment extends Fragment implements PositionUpdateListener, DismissListener {

    View mainView;

    private EmptyStateRecyclerView surveyList;
    private int LAST_CLICKED_POSITION = -1;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    private ArrayList<Survey> SURVEY_LIST = new ArrayList<>();
    SurveyAdapter adapter;
    private int SHOWCASE_POSITION = 0;
    LinearLayoutManager linearLayoutManager;

    public static Handler.Callback callback;

    public SurveyFragment() {

    }

    public void onResumeFragment() {
        if (LAST_CLICKED_POSITION != -1) {
            getSurveyList();
            LAST_CLICKED_POSITION = -1;
        }
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_survey, 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();
        surveyList = mainView.findViewById(R.id.surveyList);
        surveyList.setHasFixedSize(true);
        surveyList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getActivity());
        surveyList.setLayoutManager(linearLayoutManager);
        surveyList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(getActivity(), "No data available", ""));
        callback = msg -> {
            getSurveyList();
            return false;
        };


        if (StorePreference.getInstance(getActivity()).getBooleanValue(GlobalData.ISDSELOGIN))
            sendFirstHitCountToServer();

        //   getSurveyList();

    }


    private void sendFirstHitCountToServer() {
        restService.sendAllHitCount(buildFirstConfigData()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {

                    Log.e("responeHit", response.body().getMessage());
                } else {
                    assert response.body() != null;
                    Log.e("responeHit", response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("responeHit", t.getMessage());
                }
            }
        });
    }

    private HitCountModel buildFirstConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Feedback");
        hitCountModel.setViewtime("0");
        return hitCountModel;
    }

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

            try {
                restService.getSurveyList().enqueue(new MyCallback<SurveyResponse>() {
                    @Override
                    public void onResponse(Call<SurveyResponse> call, Response<SurveyResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            SURVEY_LIST = response.body().getData();
                            if (SURVEY_LIST == null) {
                                SURVEY_LIST = new ArrayList<>();
                            }
                            if (SURVEY_LIST.size() == 0) {
                                surveyList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                            } else {
                                surveyList.invokeState(EmptyStateRecyclerView.STATE_OK);
                            }
                            adapter = new SurveyAdapter(getActivity(), SURVEY_LIST,
                                    SurveyFragment.this);
                            surveyList.setAdapter(adapter);
                        } 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<SurveyResponse> 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();
        }
    }


    @Override
    public void onPositionUpdate(int position) {
        LAST_CLICKED_POSITION = position;
    }

//    public View getSpinner() {
//        return surveySpinner;
//    }


    @Override
    public void onDismiss(String id) {
        try {
            if (SHOWCASE_POSITION == 0) {
                View view;
                if (adapter.getItemCount() > 0) {
                    view = Objects.requireNonNull(surveyList.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition())).itemView;
                } else {
                    view = surveyList;
                }
                new FancyShowCaseView.Builder(Objects.requireNonNull(getActivity()))
                        .focusOn(view)
                        .title("Tap here attend survey")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.ROUNDED_RECTANGLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            }
            SHOWCASE_POSITION++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSkipped(String id) {

    }
}
