package com.cygnusa.hyperm.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.cygnusa.hyperm.DSEViewFeedbackActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.pickimage.util.FixedGridLayoutManager;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.wrappers.DSEFeedbackResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DSEFeedBackFragment extends Fragment {

    HorizontalScrollView headerScroll;
    RecyclerView rcvDynamicView;
    TextView txtNoDataFound;
    int scrollX = 0;
    ApiService restService;
    public DseFeedbackAdapter feedbackAdapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dse_feedback_marking, container, false);
        initView(view);
        setUpRecyclerView();

        rcvDynamicView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                scrollX += dx;

                headerScroll.scrollTo(scrollX, 0);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

        getDseFeedback();

        return view;
    }

    private void getDseFeedback() {
        restService.getDSEFeedback().enqueue(new Callback<DSEFeedbackResponse>() {
            @Override
            public void onResponse(Call<DSEFeedbackResponse> call, Response<DSEFeedbackResponse> response) {
                if (response.body() != null) {
                    if (response.body().getMessage().equalsIgnoreCase("Success")) {
                        if (response.body().getFeedBackData() != null && response.body().getFeedBackData().size() > 0) {
                            txtNoDataFound.setVisibility(View.GONE);
                            rcvDynamicView.setVisibility(View.VISIBLE);
                            GlobalData.DSEFEEDBACKRESPONSEGROUPIMAGE = response.body().getFeedBackData().get(0).getTraining_group_image();
                            feedbackAdapter = new DseFeedbackAdapter(response.body().getFeedBackData());
                            rcvDynamicView.setAdapter(feedbackAdapter);
                        } else {
                            txtNoDataFound.setVisibility(View.VISIBLE);
                            rcvDynamicView.setVisibility(View.GONE);
                        }
                    } else {
                        GlobalData.toast(getActivity(), response.body().getMessage());
                    }
                } 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;
                        getActivity().finish();
                    }
                }
            }

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

            }
        });

    }

    private void setUpRecyclerView() {

        FixedGridLayoutManager manager = new FixedGridLayoutManager();
        manager.setTotalColumnCount(1);
        rcvDynamicView.setLayoutManager(manager);
    }

    private void initView(View view) {
        headerScroll = view.findViewById(R.id.headerScroll);
        rcvDynamicView = view.findViewById(R.id.rcvDynamicView);
        txtNoDataFound = view.findViewById(R.id.txtNoDataFound);
        txtNoDataFound.setVisibility(View.GONE);
        restService = ((MainApplication) getActivity().getApplication()).getClient();

    }

    private class DseFeedbackAdapter extends RecyclerView.Adapter<DSEFeedbackViewHolder> {
        List<DSEFeedbackResponse.DSEFeedbackData> feedBackData;

        public DseFeedbackAdapter(List<DSEFeedbackResponse.DSEFeedbackData> data) {
            feedBackData = data;
        }

        @NonNull
        @Override
        public DSEFeedbackViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.dse_feedback_holder, parent, false);
            return new DSEFeedbackViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull DSEFeedbackViewHolder holder, int position) {
            holder.overall_feedback.setText(feedBackData.get(position).getOverallFeedback());
            holder.trainer_feedback.setText(feedBackData.get(position).getTrainerFeedback());
            holder.training_feedback.setText(feedBackData.get(position).getTrainingFeedback());
            holder.training_title.setText(feedBackData.get(position).getTitle());
            holder.training_id.setText(feedBackData.get(position).getTraining_id());
            holder.trainer_name.setText(feedBackData.get(position).getOrganizer_name());
            holder.total_participant.setText(feedBackData.get(position).getTotal_participants());

            if (feedBackData.get(position).getIs_completed().equalsIgnoreCase("1")) {
                holder.btnCertification.setEnabled(false);
                holder.btnCertification.setText("Feedback Completed");
                holder.btnCertification.setAlpha(.7f);
            } else {
                holder.btnCertification.setEnabled(true);
                holder.btnCertification.setAlpha(1f);
                holder.btnCertification.setText("Enter Feedback");
            }


            String endDate = feedBackData.get(position).getEndDate();
            String startDate = feedBackData.get(position).getStartDate();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String startDateString = "", endDateString = "";
            try {
                startDateString = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Objects.requireNonNull(format.parse(startDate)));
                endDateString = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Objects.requireNonNull(format.parse(endDate)));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            holder.trining_dates.setText(startDateString + " - " + endDateString);

            holder.btnCertification.setTag(position);
            holder.btnCertification.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GlobalData.DSEFEEDBACKVIEW = feedBackData.get((Integer) v.getTag());
                    startActivity(new Intent(getActivity(), DSEViewFeedbackActivity.class));
                    getActivity().finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return feedBackData.size();
        }
    }

    private static class DSEFeedbackViewHolder extends RecyclerView.ViewHolder {
        TextView training_title, trining_dates, training_feedback, trainer_feedback, overall_feedback, training_id, trainer_name, total_participant;
        Button btnCertification;

        public DSEFeedbackViewHolder(@NonNull View itemView) {
            super(itemView);

            training_title = itemView.findViewById(R.id.training_title);
            trining_dates = itemView.findViewById(R.id.trining_dates);
            training_feedback = itemView.findViewById(R.id.training_feedback);
            trainer_feedback = itemView.findViewById(R.id.trainer_feedback);
            overall_feedback = itemView.findViewById(R.id.overall_feedback);
            training_id = itemView.findViewById(R.id.training_id);
            trainer_name = itemView.findViewById(R.id.trainer_name);
            total_participant = itemView.findViewById(R.id.total_participant);


            btnCertification = itemView.findViewById(R.id.btnCertification);

        }
    }
}
