package com.ttiglobal.inttilectgpchat.training.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.adapter.HistoryAdapter;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MyCallback;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.CommonResponse;

import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Response;

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

    private List<Schedules> items;
    private Context context;
    private Dialog dialog;
    private int lastExpandedPosition = -1;
    private ExpandableListView modeList;
    private ApiService restClient;
    private TransparentProgressDialog progressDialog;

    ScheduleAdapter(Context context, List<Schedules> items, ApiService restClient) {
        this.items = items;
        this.context = context;
        this.restClient = restClient;
    }

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

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Schedules model = items.get(position);
        holder.nbSender.setText(String.format("Presenter : %s", model.getOrganiser_name()));
        holder.nbContent.setText(model.getDescription());
        holder.nbTitle.setText(model.getTitle());

        holder.nbDate.setText(model.getDate());
        holder.nbMonth.setText(model.getMonth());
        holder.nbTime.setText(model.getTime());

        holder.join.setTag(model);
        holder.join.setOnClickListener(view -> {
            Schedules mSchedules = (Schedules) view.getTag();
            Gson gson = new Gson();
            JsonElement jsonElement = gson.toJsonTree(
                    mSchedules, new TypeToken<Schedules>() {
                    }.getType());

            Intent i = new Intent(context, JitsiActivity.class);
            JitsiActivity.SCHEDULE = mSchedules;
            JitsiActivity.isBroadcaster = (mSchedules.getOrganiser().trim().equalsIgnoreCase(GlobalData.user.getData().getEmp_code().trim()));
            context.startActivity(i);
        });

        holder.info.setTag(model);

        boolean isPresendor = (model.getOrganiser().trim().equalsIgnoreCase(GlobalData.user.getData().getEmp_code().trim()));
        if (isPresendor) {
            holder.info.setVisibility(View.VISIBLE);
        } else {
            holder.info.setVisibility(View.INVISIBLE);
        }

        holder.info.setOnClickListener(view -> {
            Schedules mSchedules = (Schedules) view.getTag();
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View mView = LayoutInflater.from(context).inflate(R.layout.training_popup_history, null);
            ImageButton close = mView.findViewById(R.id.closeButton);
            TextView title = mView.findViewById(R.id.title);
            TextView addNewParticipant = mView.findViewById(R.id.addNewParticipant);
            addNewParticipant.setVisibility(View.GONE);
            if (!mSchedules.isValidTime()) {
                if (!mSchedules.isEnded()) {
                    addNewParticipant.setVisibility(View.VISIBLE);
                }
            }

            addNewParticipant.setTag(mSchedules);
            addNewParticipant.setOnClickListener(mView1 -> {
                dialog.dismiss();
                AddParticipantActivity.SCHEDULE = (Schedules) mView1.getTag();
                context.startActivity(new Intent(context, AddParticipantActivity.class));
            });

            modeList = mView.findViewById(R.id.listView);
            title.setText("Participants");
            close.setOnClickListener(view1 -> dialog.dismiss());
            HistoryAdapter modeAdapter = new HistoryAdapter(context, mSchedules, restClient);
            modeList.setAdapter(modeAdapter);
            lastExpandedPosition = -1;

            modeList.setOnGroupExpandListener(groupPosition -> {
                if (lastExpandedPosition != -1
                        && groupPosition != lastExpandedPosition) {
                    modeList.collapseGroup(lastExpandedPosition);
                }
                lastExpandedPosition = groupPosition;
            });

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

        holder.removeTraining.setVisibility(View.GONE);

        if (model.getStatus().equalsIgnoreCase("2")) {
            holder.join.setEnabled(false);
            holder.join.setText("Ended");
        } else {
            if (model.isValidTime(isPresendor)) {
                holder.join.setEnabled(true);
                holder.join.setText("Join");
                if (isPresendor) {
                    if (!model.isValidTime()) {
                        if (!model.isEnded()) {
                            holder.removeTraining.setVisibility(View.VISIBLE);
                        }
                    }
                }
            } else {
                holder.join.setEnabled(false);
                if (model.isEnded()) {
                    holder.join.setText("Ended");
                } else {
                    holder.join.setText("Yet to be Start");
                    if (isPresendor) {
                        holder.removeTraining.setVisibility(View.VISIBLE);
                    }
                }
            }
        }


        holder.removeTraining.setTag(model);
        holder.removeTraining.setOnClickListener(view -> {
            final Schedules mSchedules = (Schedules) view.getTag();
            new androidx.appcompat.app.AlertDialog.Builder(context)
                    .setMessage("Are you sure to remove?")
                    .setTitle(mSchedules.getTitle())
                    .setPositiveButton("Yes",
                            (dialog, which) -> removeTraining(mSchedules)).setNegativeButton("No", null).show();
        });
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }

    public void add(Schedules item, int position) {
        items.add(position, item);
        notifyItemInserted(position);
    }

    public void add(Schedules item) {
        items.add(item);
        notifyItemInserted(items.size());
    }

    public void remove(int position) {
        items.remove(position);
        notifyItemRemoved(position);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        View view;
        CardView cardView;
        TextView nbDate, nbTitle, nbContent, nbSender, nbMonth, nbTime;
        Button join;
        ImageButton info, removeTraining;

        private ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            cardView = itemView.findViewById(R.id.cardView);
            nbDate = itemView.findViewById(R.id.nbDate);
            nbTitle = itemView.findViewById(R.id.nbTitle);
            nbContent = itemView.findViewById(R.id.nbContent);
            nbSender = itemView.findViewById(R.id.nbSender);
            join = itemView.findViewById(R.id.join);
            info = itemView.findViewById(R.id.info);
            nbMonth = itemView.findViewById(R.id.nbMonth);
            nbTime = itemView.findViewById(R.id.nbTime);
            removeTraining = itemView.findViewById(R.id.removeTraining);
        }
    }

    private void removeTraining(Schedules schedules) {
        if (new UtilService().isNetworkAvailable(Objects.requireNonNull(context))) {
            try {
                progressDialog = new TransparentProgressDialog(context);
                progressDialog.setCancelable(true);
                progressDialog.show();

                restClient.removeTraining(schedules.getId()).enqueue(new MyCallback<CommonResponse>(schedules) {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.isSuccessful()) {
                            Toast.makeText(context, "Training removed", Toast.LENGTH_SHORT).show();
                            int pos = items.indexOf(cbSchedules);
                            items.remove(cbSchedules);
                            notifyItemRemoved(pos);
                        } else {
                            Toast.makeText(context, "Unable to remove, try again!", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        Toast.makeText(context, "Unable to remove, try again!", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Toast.makeText(context, "Unable to remove, try again!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
