package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

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.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.SingleDataList;

import org.joda.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 AcceptTrainingActivity extends AppCompatActivity {

    private TextView txtTrainingUID, txtTrainingName, txtTrainerName, txtBusinessSegment, txtTotalParticipant;
    private TextView txtSubmissionDays, txtTrainingStartDate, txtTrainingEndDate, txtTrainingVenue;
    private Button btnAcknowledge;
    private LinearLayout layoutDate;
    private TransparentProgressDialog progressDialog;
    ApiService apiService;
    String scheduleId = "";
    private static String btnStatus;
    private String businessSegment;

    private String id1;
    private String id2;
    List<String> eTime = new ArrayList<>();
    List<String> sTime = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //JodaTimeAndroid.init(this);
        setContentView(R.layout.fragment_accept_training);
        initView();
    }

    private void initView() {

        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);

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

        txtTrainingUID = findViewById(R.id.txtTrainingUID);
        txtTrainingName = findViewById(R.id.txtTrainingName);
        txtTrainerName = findViewById(R.id.txtTrainerName);
        txtBusinessSegment = findViewById(R.id.txtBusinessSegment);
        txtTotalParticipant = findViewById(R.id.txtTotalParticipant);
        txtSubmissionDays = findViewById(R.id.txtSubmissionDays);
        txtTrainingStartDate = findViewById(R.id.txtTrainingStartDate);
        txtTrainingEndDate = findViewById(R.id.txtTrainingEndDate);
        txtTrainingVenue = findViewById(R.id.txtTrainingVenue);

        btnAcknowledge = findViewById(R.id.btnAcknowledge);
        layoutDate = findViewById(R.id.layoutDate);

        if (GlobalData.scheduledDataList != null && GlobalData.scheduledDataList.size() > 0) {
            String userID = GlobalData.scheduledDataList.get(0).getUserid();

            if (GlobalData.scheduledDataList.get(0).getParticipant() != null && GlobalData.scheduledDataList.get(0).getParticipant().size() > 0)
                for (int i = 0; i < GlobalData.scheduledDataList.get(0).getParticipant().size(); i++) {
                    if (GlobalData.scheduledDataList.get(0).getParticipant().get(i).getUserid().equalsIgnoreCase(userID)) {
                        btnStatus = GlobalData.scheduledDataList.get(0).getParticipant().get(i).getStatus();
                    }
                }

            String startDate = GlobalData.scheduledDataList.get(0).getStartDate();
            String endDate = GlobalData.scheduledDataList.get(0).getEndDate();

            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 s = GlobalData.scheduledDataList.get(0).getStartdate();
            String e = GlobalData.scheduledDataList.get(0).getEnddate();

            LocalDate start = LocalDate.parse(s);
            LocalDate end = LocalDate.parse(e);
            List<LocalDate> totalDates = new ArrayList<>();
            while (!start.isAfter(end)) {
                totalDates.add(start);

                start = start.plusDays(1);
            }

            String startTime = GlobalData.scheduledDataList.get(0).getStarttime();
            String endTime = GlobalData.scheduledDataList.get(0).getEndtime();

            try {
                JSONArray arrayFromTime = new JSONArray(startTime);
                for (int i = 0; i < arrayFromTime.length(); i++) {
                    id1 = (String) arrayFromTime.get(i);
                    sTime.add(id1);
                }
                JSONArray arrayToTime = new JSONArray(endTime);
                for (int i = 0; i < arrayToTime.length(); i++) {
                    id2 = (String) arrayToTime.get(i);
                    eTime.add(id2);
                }
            } catch (JSONException e1) {
                sTime.add(startTime);
                eTime.add(endTime);
                e1.printStackTrace();
            }

            int trainingDays = Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays());

            for (int i = 0; i < trainingDays; i++) {
                TextView txtDays = new TextView(this);
                txtDays.setTextSize(15);
                txtDays.setTextColor(Color.parseColor("#00344C"));
                txtDays.setPadding(150, 0, 0, 0);
                if (sTime.size() - 1 >= i && eTime.size() - 1 >= i)
                    txtDays.setText("Day " + (i + 1) + " : " + totalDates.get(i) + " " + sTime.get(i) + " - " + eTime.get(i));
                txtDays.setTypeface(Typeface.DEFAULT_BOLD);
                layoutDate.addView(txtDays);
            }
            if (GlobalData.scheduledDataList.get(0).getBusinessSegment().equalsIgnoreCase("1")) {
                businessSegment = "Scooter";
            } else if (GlobalData.scheduledDataList.get(0).getBusinessSegment().equalsIgnoreCase("2")) {
                businessSegment = "Motorcycle";
            } else if (GlobalData.scheduledDataList.get(0).getBusinessSegment().equalsIgnoreCase("3")) {
                businessSegment = "Scooter & Motorcycle";
            }
            txtTrainingName.setText(GlobalData.scheduledDataList.get(0).getTitle());
            txtTrainerName.setText(GlobalData.scheduledDataList.get(0).getOrganizerName());
            txtBusinessSegment.setText(businessSegment);
            if (GlobalData.scheduledDataList.get(0).getParticipant() != null && GlobalData.scheduledDataList.get(0).getParticipant().size() > 0)
                txtTotalParticipant.setText(String.valueOf(GlobalData.scheduledDataList.get(0).getParticipant().size()));
            txtSubmissionDays.setText(String.valueOf(GlobalData.scheduledDataList.get(0).getTrainingDays() + " Days"));
            txtTrainingStartDate.setText(startDateString);
            txtTrainingEndDate.setText(endDateString);
            txtTrainingVenue.setText(GlobalData.scheduledDataList.get(0).getVenueAddress());
            txtTrainingUID.setText(GlobalData.scheduledDataList.get(0).getTraining_id());
        }

        btnAcknowledge.setOnClickListener(v -> {
            if (btnStatus.equalsIgnoreCase("0")) {
                GlobalData.scheduledDataList.get(0).getParticipant().get(0).setAcknowledge_by("2");
                sendAcknowledge("1");
            }
        });

        if (btnStatus.equalsIgnoreCase("1")) {
            if (GlobalData.scheduledDataList.get(0).getParticipant().get(0).getAcknowledge_by() != null)
                if (GlobalData.scheduledDataList.get(0).getParticipant().get(0).getAcknowledge_by().equalsIgnoreCase("1")) {
                    btnAcknowledge.setText("Acknowledged by AM");
                } else if (GlobalData.scheduledDataList.get(0).getParticipant().get(0).getAcknowledge_by().equalsIgnoreCase("2")) {
                    btnAcknowledge.setText("Acknowledged by DSE");
                }
            ColorStateList colorStateList = ContextCompat.getColorStateList(this, R.color.btn_green);
            btnAcknowledge.setBackgroundTintList(colorStateList);
        } else if (btnStatus.equalsIgnoreCase("2")) {
            btnAcknowledge.setText("Declined");
            ColorStateList colorStateList = ContextCompat.getColorStateList(this, R.color.btn_red);
            btnAcknowledge.setBackgroundTintList(colorStateList);
        }


    }

    private void sendAcknowledge(String status) {

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


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

        apiService.sendAcknowledge(map).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();
                    onBackPressed();
                } 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 setAllDataDSELogin(SingleDataList singleDataList) {

        if (singleDataList != null) {
            txtTrainingName.setText(singleDataList.getTitle());

            scheduleId = singleDataList.getScheduleId();

            String endDate = singleDataList.getEndDate();
            String startDate = singleDataList.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 = singleDataList.getEndDate();
            String startTime = singleDataList.getStartDate();

            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);

        }
    }

    @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);
    }
}
