package com.cygnusa.hyperm.adapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.tooltip.Tooltip;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.ReasonList;
import com.cygnusa.hyperm.wrappers.ReasonListResponse;
import com.cygnusa.hyperm.wrappers.ScheduleData;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

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

public class ASMParticipantListAdapter extends RecyclerView.Adapter<ASMParticipantListAdapter.ViewHolder> {

    private List<ScheduleData> ParticipantList;
    private Context context;
    private ApiService restService;
    private List<ReasonList> REASONS = new ArrayList<>();
    private String[] reasonName = {"None"};
    private String[] reasonId = {"None"};
    private String reasonIdString = "", reasonNameString;
    private TextView txtDecline;
    private Dialog dialog;
    private String dseName, dealerName, amName, userID;

    public ASMParticipantListAdapter(Context context, List<ScheduleData> items, ApiService restClient) {
        this.ParticipantList = items;
        this.context = context;
        this.restService = restClient;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ScheduleData scheduleData = ParticipantList.get(0);
        holder.view.setTag(scheduleData);


        String endDate = GlobalData.scheduledDataList.get(0).getEndDate();
        String startDate = GlobalData.scheduledDataList.get(0).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.txtDSEName.setText(scheduleData.getParticipant().get(position).getName() + " - "
                + scheduleData.getParticipant().get(position).getSmpin());
        holder.txtDealerName.setText(scheduleData.getParticipant().get(position).getDealerName());
        holder.txtAMName.setText(scheduleData.getParticipant().get(position).getAmName());
        holder.txtTitle.setText(scheduleData.getTitle());
        holder.txtTrainerName.setText(scheduleData.getOrganizerName());
        holder.txtDate.setText(startDateString + " - " + endDateString);

        String trainingResponseStatus = GlobalData.scheduledDataList.get(0).getParticipant().get(position).getStatus();


        if (trainingResponseStatus.equalsIgnoreCase("1")) {
            if (GlobalData.scheduledDataList.get(0).getParticipant().get(position).getAcknowledge_by().equalsIgnoreCase("1")) {
                holder.btnAcknowledge.setText("Acknowledged by AM");
            } else if (GlobalData.scheduledDataList.get(0).getParticipant().get(position).getAcknowledge_by().equalsIgnoreCase("2")) {
                holder.btnAcknowledge.setText("Acknowledged by DSE");
            }
            ColorStateList colorStateList = ContextCompat.getColorStateList(context, R.color.btn_green);
            holder.btnAcknowledge.setBackgroundTintList(colorStateList);
        } else if (trainingResponseStatus.equalsIgnoreCase("2")) {
            ColorStateList colorStateList = ContextCompat.getColorStateList(context, R.color.btn_red);
            holder.btnDecline.setBackgroundTintList(colorStateList);
            holder.txtTitle.setTextColor(Color.parseColor("#F90303"));
            holder.imgInfo.setVisibility(View.VISIBLE);
        }

        holder.imgInfo.setTag(position);
        holder.imgInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String header = scheduleData.getParticipant().get((Integer) v.getTag()).getDeclineReasonDesc();
                View mView = LayoutInflater.from(context).inflate(R.layout.tooltip_layout, null);
                TextView text = mView.findViewById(R.id.text11);
                TextView txtReasonTitle = mView.findViewById(R.id.txtReasonTitle);
//                if (scheduleData.getParticipant().get((Integer) v.getTag()).getDeclineReasonName() != null && !scheduleData.getParticipant().get((Integer) v.getTag()).getDeclineReasonName().equalsIgnoreCase(""))
//                    txtReasonTitle.setText(scheduleData.getParticipant().get((Integer) v.getTag()).getDeclineReasonName());
                text.setText(header);
                Tooltip.TooltipView tooltip = Tooltip.make(context,
                        new Tooltip.Builder(101)
                                .anchor(v, Tooltip.Gravity.TOP)
                                .closePolicy(new Tooltip.ClosePolicy()
                                        .insidePolicy(true, false)
                                        .outsidePolicy(true, false), 0)
                                .activateDelay(300)
                                .withStyleId(R.style.ToolTipLayoutCustomStyle)
                                .showDelay(300)
                                .text("")
                                .setBgColor(context.getResources().getColor(R.color.bg_white))
                                .view(mView)
                                .maxWidth(300)
                                .withArrow(true)
                                .build()
                );
                tooltip.setTextColor(R.color.material_bluegrey800);
                tooltip.show();
            }
        });
        holder.btnDecline.setTag(position);
        holder.btnDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (trainingResponseStatus.equalsIgnoreCase("0")) {
                    openPopup((Integer) v.getTag());
                }
            }
        });
        holder.btnAcknowledge.setTag(position);
        holder.btnAcknowledge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (trainingResponseStatus.equalsIgnoreCase("0")) {
                    GlobalData.scheduledDataList.get(0).getParticipant().get((Integer) v.getTag()).setAcknowledge_by("1");
                    sendAcknowledge("1", scheduleData.getParticipant().get((Integer) v.getTag()).getUserid(), "", "", (Integer) v.getTag());
                }
            }
        });

        getReasons();
    }

    @Override
    public int getItemCount() {
        return GlobalData.scheduledDataList.get(0).getParticipant().size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView txtDSEName, txtDealerName, txtAMName, txtTitle, txtTrainerName, txtDate;
        Button btnDecline, btnAcknowledge;
        ImageView imgInfo;
        View view;

        private ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            txtDSEName = itemView.findViewById(R.id.txtDSEName);
            txtDealerName = itemView.findViewById(R.id.txtDealerName);
            txtAMName = itemView.findViewById(R.id.txtAMName);
            txtTitle = itemView.findViewById(R.id.txtTitle);
            txtTrainerName = itemView.findViewById(R.id.txtTrainerName);
            txtDate = itemView.findViewById(R.id.txtDate);

            btnAcknowledge = itemView.findViewById(R.id.btnAcknowledge);
            btnDecline = itemView.findViewById(R.id.btnDecline);

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

            //   if (GlobalData.scheduledDataList.get(0).getAttendanceUpdateStatus().equalsIgnoreCase("1")) {
//            btnAcknowledge.setEnabled(false);
//            btnDecline.setEnabled(false);
            //  }
        }
    }

    private void sendAcknowledge(String status, String userID, String reasonID, String reasonDes, int position) {

        HashMap<String, String> map = new HashMap<>();
        map.put("schedule_id", GlobalData.scheduledDataList.get(0).getScheduleId());
        map.put("userid", userID);
        map.put("status", status);
        map.put("acknowledge_by", "1");
        map.put("decline_reason", reasonID);
        map.put("decline_reason_desc", reasonDes);

        restService.sendAcknowledge(map).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (status.equalsIgnoreCase("2")) {
                        GlobalData.scheduledDataList.get(0).getParticipant().get(position).setStatus("2");
                        GlobalData.scheduledDataList.get(0).getParticipant().get(position).setDeclineReasonDesc(reasonDes);
                    } else {
                        GlobalData.scheduledDataList.get(0).getParticipant().get(position).setStatus("1");
                    }
                    if (dialog != null && dialog.isShowing())
                        dialog.dismiss();
                    notifyDataSetChanged();
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(context, message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                    }
                }
            }

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

            }
        });
    }

    private void getReasons() {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(context))) {
            try {
                restService.getReasonList().enqueue(new Callback<ReasonListResponse>() {
                    @Override
                    public void onResponse(Call<ReasonListResponse> call, Response<ReasonListResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null && response.body().getData().size() > 0) {
                                REASONS = response.body().getData();
                                reasonName = new String[REASONS.size()];
                                reasonId = new String[REASONS.size()];
                                for (int i = 0; i < response.body().getData().size(); i++) {
                                    reasonName[i] = REASONS.get(i).getName();
                                    reasonId[i] = REASONS.get(i).getId();
                                }
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                        } else if (response.body() != null) {
                            GlobalData.showToast(context, 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(context, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ReasonListResponse> call, Throwable t) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void settitleSelction(int position, EditText edtReason) {
        int selection = 0;
        if (!txtDecline.getText().toString().isEmpty()) {
            selection = Arrays.asList(reasonName).indexOf(txtDecline.getText().toString().trim());
        }
        new AlertDialog.Builder(context).setTitle("Reason for Reschedule")
                .setSingleChoiceItems(reasonName, selection, null)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", (dialog, whichButton) -> {
                    dialog.dismiss();
                    int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    txtDecline.setText(reasonName[selectedPosition]);
                    if (reasonName[selectedPosition].equalsIgnoreCase("other"))
                        edtReason.setVisibility(View.VISIBLE);
                    reasonIdString = reasonId[selectedPosition];
                    reasonNameString = reasonName[selectedPosition];
                    //ParticipantList.get(0).getParticipant().get(position).setDeclineReasonDesc(reasonName[selectedPosition]);
                })
                .show();
    }

    public void openPopup(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View mView = LayoutInflater.from(context).inflate(R.layout.decline_popup, null);
        txtDecline = mView.findViewById(R.id.txtDecline);
        TextView txtHeader = mView.findViewById(R.id.txtHeader);
        EditText edtReason = mView.findViewById(R.id.edtReason);
        Button btnCancel = mView.findViewById(R.id.btnCancel);
        Button btnSubmit = mView.findViewById(R.id.btnSubmit);

        edtReason.setVisibility(View.GONE);

        for (int i = 0; i < GlobalData.scheduledDataList.get(0).getParticipant().size(); i++) {
            dseName = GlobalData.scheduledDataList.get(0).getParticipant().get(position).getName() + " - "
                    + GlobalData.scheduledDataList.get(0).getParticipant().get(position).getSmpin();
            dealerName = GlobalData.scheduledDataList.get(0).getParticipant().get(position).getDealerName();
            amName = GlobalData.scheduledDataList.get(0).getParticipant().get(position).getAmName();
            userID = GlobalData.scheduledDataList.get(0).getParticipant().get(position).getUserid();
        }

        String header = "Do you want to Decline the classroom request for " +
                "DSE Name : " + dseName + "/Dealer Name : " + dealerName + "/Area Manager : " + amName + "";

        txtHeader.setText(header);

        ImageView imgDecline = mView.findViewById(R.id.imgDecline);

        txtDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settitleSelction(position, edtReason);
            }
        });

        imgDecline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settitleSelction(position, edtReason);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!txtDecline.getText().toString().isEmpty()) {
                    setSelectedData(position, reasonNameString, edtReason.getText().toString());

                    sendAcknowledge("2", userID, reasonIdString, reasonNameString, position);
                    notifyDataSetChanged();
                } else {
                    GlobalData.toast(context, "Select the reason");
                }
            }
        });

        builder.setView(mView);
        dialog = builder.create();
        dialog.show();

    }

    private void setSelectedData(int position, String reasonNameString, String toString) {
        ParticipantList.get(0).getParticipant().get(position).setDeclineReason(reasonNameString);
    }
}
