package com.cygnusa.hyperm.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.wrappers.DSETrainingFeedbackData;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;

import static com.cygnusa.hyperm.util.GlobalData.trainerSum;

public class DSETrainerFeedback extends Fragment {

    private TextView noDataFound, hintText, txtScore;
    ;
    private RecyclerView rcvTrainingFeedbackList;
    DSETrainerAdapter adapter;

    Activity activity;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dse_training_feedback, container, false);
        initViews(view);
        return view;
    }

    private void initViews(View view) {
        activity = getActivity();
        noDataFound = view.findViewById(R.id.noDataFound);
        hintText = view.findViewById(R.id.hintText);
        txtScore = view.findViewById(R.id.score);

        hintText.setText("Over all Trainer Feedback score");

        rcvTrainingFeedbackList = view.findViewById(R.id.rcvSummaryList);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcvTrainingFeedbackList.setLayoutManager(manager);

        if (GlobalData.DSEFeedbackQuestions != null) {
            noDataFound.setVisibility(View.GONE);
            rcvTrainingFeedbackList.setVisibility(View.VISIBLE);
            ArrayList<DSETrainingFeedbackData.DSETrainingQuestion> questions = new ArrayList<>();
            if (GlobalData.DSEFeedbackQuestions.getQuestions() != null)
                for (int k = 0; k < GlobalData.DSEFeedbackQuestions.getQuestions().size(); k++) {
                    if (GlobalData.DSEFeedbackQuestions.getQuestions().get(k).getQuestiontype().equalsIgnoreCase("2")) {
                        questions.add(GlobalData.DSEFeedbackQuestions.getQuestions().get(k));
                    }
                }
            adapter = new DSETrainerAdapter(questions, getActivity());
            rcvTrainingFeedbackList.setAdapter(adapter);
        } else {
            noDataFound.setVisibility(View.VISIBLE);
            rcvTrainingFeedbackList.setVisibility(View.GONE);

        }

    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView question;
        public TextView score;
        public ImageView levelSpinner;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            question = itemView.findViewById(R.id.questions);
            score = itemView.findViewById(R.id.score);
            levelSpinner = itemView.findViewById(R.id.levelSpinner);
            levelSpinner.setVisibility(View.VISIBLE);
        }
    }


    class DSETrainerAdapter extends RecyclerView.Adapter<DSETrainerFeedback.ViewHolder> {
        ArrayList<DSETrainingFeedbackData.DSETrainingQuestion> questionData;
        private Context activity;
        private String[] TRAINING_TITLES;
        private int TRAINING_POSITION = -1;
        int pos = 0;
        int totalScore = 0;


        public DSETrainerAdapter(ArrayList<DSETrainingFeedbackData.DSETrainingQuestion> summaryData, FragmentActivity activity) {
            questionData = summaryData;
            this.activity = activity;
        }

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


        @Override
        public void onBindViewHolder(@NonNull DSETrainerFeedback.ViewHolder holder, int position) {
            if (questionData.get(position).getQuestiontype().equalsIgnoreCase("2")) {
                holder.question.setText(questionData.get(position).getQuestiontext());
                holder.score.setText(questionData.get(position).getSelectedOption());
                if (questionData.get(position).getRatingOptions() != null && questionData.get(position).getRatingOptions().size() > 0) {
                    TRAINING_TITLES = new String[questionData.get(position).getRatingOptions().size()];
                    for (int i = 0; i < questionData.get(position).getRatingOptions().size(); i++) {
                        TRAINING_TITLES[i] = questionData.get(position).getRatingOptions().get(i).getOptions();
                    }
                }

                float training = 0;

                for (int k = 0; k < questionData.size(); k++) {
                    if (questionData.get(k).getSelectedOption() != null)
                        training = training + Integer.parseInt(questionData.get(k).getSelectedOption());
                }
                trainerSum = training / questionData.size();
                txtScore.setText(new DecimalFormat("##.##").format(trainerSum));
            }


            holder.levelSpinner.setTag(position);
            holder.levelSpinner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setScore(holder.score, (Integer) v.getTag(), questionData.get((Integer) v.getTag()).getQid());

                }
            });

            holder.score.setTag(position);
            holder.score.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setScore(holder.score, (Integer) v.getTag(), questionData.get((Integer) v.getTag()).getQid());
                }
            });
        }

        private void setScore(TextView score, int position, String qid) {
            int selection = 0;
            if (!score.getText().toString().isEmpty()) {
                selection = Arrays.asList(TRAINING_TITLES).indexOf(score.getText().toString().trim());
            }
            new AlertDialog.Builder(activity).setTitle("Select Score")
                    .setSingleChoiceItems(TRAINING_TITLES, selection, null)
                    .setNegativeButton("Cancel", null)
                    .setPositiveButton("Ok", (dialog, whichButton) -> {
                        dialog.dismiss();
                        int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                        score.setText(TRAINING_TITLES[selectedPosition]);
                        TRAINING_POSITION = selectedPosition;
                        questionData.get(position).setSelectedOption(TRAINING_TITLES[selectedPosition]);
                        for (int k = 0; k < GlobalData.DSEFeedbackQuestions.getQuestions().size(); k++) {
                            if (GlobalData.DSEFeedbackQuestions.getQuestions().get(k).getQid().equalsIgnoreCase(qid)) {
                                GlobalData.DSEFeedbackQuestions.getQuestions().get(k).
                                        setSelectedOption(TRAINING_TITLES[selectedPosition]);
                            }
                        }
                        notifyDataSetChanged();

                    })
                    .show();
        }

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