package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.google.gson.Gson;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
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.GetCancelOrRescheduleList;
import com.cygnusa.hyperm.wrappers.NotificationSummary;
import com.cygnusa.hyperm.wrappers.NotificationSummaryResponse;
import com.cygnusa.hyperm.wrappers.Reasons;

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

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

public class AMNotificationSummary extends AppCompatActivity {

    Button btnModify;
    private TextView txtDate, txtTime, txtLocation, txtDetails;
    RadioButton radioCancel, radioReschdule;
    private ApiService restService;
    private RelativeLayout rloutReschedule, rloutCancel;
    private List<Reasons> REASONS = new ArrayList<>();
    private String[] reasonName = {"None"};
    private String[] reasonId = {"None"};
    private TextView txtReasonReschdule, txtReasonCancel;
    private ImageButton imgReschedule, imgCancel;
    private String reasonIdString = "";
    private Button btnSubmit, btnCancel, btnList;
    ParticipantListAdapter dateAdapter;

    private TextView txtTrainingName, txtTrainingStartDate, txtTrainingStartTime, txtTrainingLevel, txtRegion,
            txtTrainingSubmissionDays, txtTrainingEndDate, txtTrainingEndTime, txtTrainingVenue, txtTrainerName, txtTrainingDuration;
    private Button accept, decline;

    String scheduleId = "";
    private TransparentProgressDialog progressDialog;
    NotificationSummary notificationSummary;

    ApiService apiService;

    public static String btnStatus = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.amnotification);

        restService = ((MainApplication) getApplication()).getClient();

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);


        accept = findViewById(R.id.accept);
        decline = findViewById(R.id.decline);
        btnList = findViewById(R.id.btnList);

        txtReasonCancel = findViewById(R.id.txtReasonCancel);
        txtTrainingLevel = findViewById(R.id.txtTrainingLevel);
        txtTrainingStartDate = findViewById(R.id.txtTrainingStartDate);
        txtTrainingStartTime = findViewById(R.id.txtTrainingStartTime);
        txtTrainingSubmissionDays = findViewById(R.id.txtTrainingSubmissionDays);
        txtTrainingEndDate = findViewById(R.id.txtTrainingEndDate);
        txtTrainingEndTime = findViewById(R.id.txtTrainingEndTime);
        txtTrainingVenue = findViewById(R.id.txtTrainingVenue);
        txtTrainingDuration = findViewById(R.id.txtTrainingDuration);
        accept = findViewById(R.id.accept);
        decline = findViewById(R.id.decline);
        txtTrainingName = findViewById(R.id.txtTrainingName);
        txtTrainerName = findViewById(R.id.txtTrainerName);
        txtRegion = findViewById(R.id.txtRegion);

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("4") ||
                GlobalData.user.getData().getRole().equalsIgnoreCase("6")) {
            decline.setVisibility(View.GONE);
            accept.setVisibility(View.GONE);
        }

        scheduleId = GlobalData.scheduledDataList.get(0).getScheduleId();


        if (btnStatus.equalsIgnoreCase("0")) {
            decline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (txtReasonCancel.getText().toString().isEmpty()) {
                        GlobalData.toast(AMNotificationSummary.this, "Choose Reason for decline");
                    } else {
//                    sendAcceptorDeclineStatus("2");
                        btnStatus = "1";
                        onBackPressed();
                    }

                }
            });

            accept.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                sendAcceptorDeclineStatus("1");
                    btnStatus = "1";
                    GlobalData.toast(AMNotificationSummary.this, "success");
                    onBackPressed();
                }
            });

        } else {
            accept.setBackgroundColor(getResources().getColor(R.color.bg_grey0));
            decline.setBackgroundColor(getResources().getColor(R.color.bg_grey0));
        }


//        txtReasonReschdule = findViewById(R.id.txtReasonReschdule);
//        imgReschedule = findViewById(R.id.imgReschedule);
        imgCancel = findViewById(R.id.imgCancel);


        txtReasonCancel.setOnClickListener(view -> {
            setCanceltitleSelction();
        });

        imgCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setCanceltitleSelction();
            }
        });

       /* if (GlobalData.mSingleDataLists != null) {
            txtDate.setText(GlobalData.mSingleDataLists.getScheduleName());


            String endDate = GlobalData.mSingleDataLists.getEndDate();
            String startDate = GlobalData.mSingleDataLists.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();
            }


            txtTime.setText(startDateString + " To " + endDateString);
            txtDetails.setText(GlobalData.mSingleDataLists.getScheduleName());
            txtLocation.setText(GlobalData.mSingleDataLists.getVenueAddress());
        }*/

        getReasons();
        getNotificationSummary();


    }

    public void SetNotification() {


        txtTrainingName.setText(GlobalData.notificationSummary.getScheduleName());


        String endDate = GlobalData.notificationSummary.getEndDate();
        String startDate = GlobalData.notificationSummary.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();
        }

        String endTime = GlobalData.notificationSummary.getEndtime();
        String startTime = GlobalData.notificationSummary.getStarttime();

        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String startTimeString = "", endTimeString = "";
        Date date1, date2;
        long difference = 0;
        try {
            date1 = timeFormat.parse(startTime);
            date2 = timeFormat.parse(endTime);
            startTimeString = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(Objects.requireNonNull(timeFormat.parse(startTime)));
            endTimeString = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(Objects.requireNonNull(timeFormat.parse(endTime)));
            difference = date1.getTime() - date2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int days = (int) (difference / (1000 * 60 * 60 * 24));
        int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
        int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);

        min = (min < 0 ? -min : min);
        Log.i("======= min", " :: " + min);

        txtTrainingLevel.setText(GlobalData.notificationSummary.getTitle());
        txtTrainerName.setText(GlobalData.notificationSummary.getOrganizerName());
        txtTrainingStartDate.setText(startDateString);
        txtTrainingEndDate.setText(endDateString);
        txtTrainingStartTime.setText(startTimeString);
        txtTrainingEndTime.setText(endTimeString);
        txtRegion.setText(GlobalData.notificationSummary.getVenueAm());
        txtTrainingDuration.setText(hours + " Hours");


    }

    private void sendAcceptorDeclineStatus(String status) {

        progressDialog = new TransparentProgressDialog(AMNotificationSummary.this);
        progressDialog.show();

        apiService.sendAcceptOrDecline(scheduleId, GlobalData.user.getData().getEmp_code(), status).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (response.body() != null) {
                    GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    finish();
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    private void getNotificationSummary() {

        progressDialog = new TransparentProgressDialog(AMNotificationSummary.this);
        progressDialog.show();

        apiService.getAMNotificationSummary(GlobalData.scheduledDataList.get(0).getScheduleId()).enqueue(new Callback<NotificationSummaryResponse>() {
            @Override
            public void onResponse(Call<NotificationSummaryResponse> call, Response<NotificationSummaryResponse> response) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (response.body() != null && response.body().getStatus() == 200) {

                    notificationSummary = response.body().getData();
                    SetNotification();

                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    finish();
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<NotificationSummaryResponse> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });
    }

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

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

    private void setCanceltitleSelction() {
        int selection = 0;
        if (!txtReasonCancel.getText().toString().isEmpty()) {
            selection = Arrays.asList(reasonName).indexOf(txtReasonCancel.getText().toString().trim());
        }
        new AlertDialog.Builder(AMNotificationSummary.this).setTitle("Reason for decline")
                .setSingleChoiceItems(reasonName, selection, null)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", (dialog, whichButton) -> {
                    dialog.dismiss();
                    int selectedPosition = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    txtReasonCancel.setText(reasonName[selectedPosition]);
                    reasonIdString = reasonId[selectedPosition];
                })
                .show();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    private class ParticipantListAdapter extends RecyclerView.Adapter<AMNotificationSummary.ParticipantViewHolder> {

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

        @Override
        public void onBindViewHolder(@NonNull ParticipantViewHolder holder, int position) {
            if (GlobalData.scheduledDataList.get(0).getParticipant().get(position).getName() == null || GlobalData.scheduledDataList.get(0).getParticipant().get(position).getName().isEmpty()) {
                holder.txtName.setText("No Name");
            } else {
                holder.txtName.setText(GlobalData.scheduledDataList.get(0).getParticipant().get(position).getName());
            }
            if (GlobalData.scheduledDataList.get(0).getParticipant().get(position).getProfilePhoto() != null || !GlobalData.scheduledDataList.get(0).getParticipant().get(position).getProfilePhoto().isEmpty()) {
                Glide.with(AMNotificationSummary.this).load(GlobalData.scheduledDataList.get(0).getParticipant().get(position).getProfilePhoto())
                        .thumbnail(Glide.with(AMNotificationSummary.this).load(R.drawable.gif_loader))
                        .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                                .placeholder(R.drawable.placeholder)).into(holder.img);
            } else {
                Glide.with(AMNotificationSummary.this).load(R.drawable.placeholder)
                        .thumbnail(Glide.with(AMNotificationSummary.this).load(R.drawable.gif_loader))
                        .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                                .placeholder(R.drawable.placeholder)).into(holder.img);
            }
        }


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

    }

    private static class ParticipantViewHolder extends RecyclerView.ViewHolder {

        TextView txtName;
        CircularImageView img;

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

            txtName = itemView.findViewById(R.id.txt_Name);
            img = itemView.findViewById(R.id.imgPic);
        }

    }
}
