package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
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.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.ASMParticipantListAdapter;
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.ErrorResponse;
import com.cygnusa.hyperm.wrappers.ViewScheduleListResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;

import net.danlew.android.joda.JodaTimeAndroid;

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.List;
import java.util.Locale;
import java.util.Objects;

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

public class ASMScheduleViewActivity extends AppCompatActivity {

    private TextView txtTrainingUID, txtTrainingName, txtTrainerName, txtBusinessSegment, txtTotalParticipant;
    private TextView txtSubmissionDays, txtTrainingStartDate, txtTrainingEndDate, txtTrainingVenue;
    private LinearLayout layoutDate, layoutTrainingDetails, layoutTraining;
    private TransparentProgressDialog progressDialog;
    private EmptyStateRecyclerView participantList;
    LinearLayoutManager linearLayoutManager;
    ASMParticipantListAdapter adapter;
    ApiService apiService;
    Boolean clickLike = true;
    private ImageView imgDown;
    private String businessSegment;
    private static String layoutVisible = "0";

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JodaTimeAndroid.init(this);
        setContentView(R.layout.asm_schedule_view);
        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();


        layoutTrainingDetails = findViewById(R.id.layoutTrainingDetails);
        layoutTraining = findViewById(R.id.layoutTraining);
        txtNoDataFound = findViewById(R.id.txtNoDataFound);
        layoutDate = findViewById(R.id.layoutDate);

        participantList = findViewById(R.id.participantList);
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        participantList.setLayoutManager(linearLayoutManager);


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

        imgDown = findViewById(R.id.imgDown);


        if (layoutVisible.equalsIgnoreCase("0")) {
            layoutTrainingDetails.setVisibility(View.GONE);
        } else {
            layoutTrainingDetails.setVisibility(View.VISIBLE);

        }

        layoutTraining.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickLike) {
                    clickLike = false;
                    layoutTrainingDetails.setVisibility(View.GONE);
                    imgDown.setImageResource(R.mipmap.down_arrow_3);
                } else {
                    clickLike = true;
                    layoutTrainingDetails.setVisibility(View.VISIBLE);
                    imgDown.setImageResource(R.mipmap.up_arrow_3);
                }
            }
        });

        imgDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickLike) {
                    clickLike = false;
                    layoutTrainingDetails.setVisibility(View.GONE);
                    imgDown.setImageResource(R.mipmap.down_arrow_3);
                } else {
                    clickLike = true;
                    layoutTrainingDetails.setVisibility(View.VISIBLE);
                    imgDown.setImageResource(R.mipmap.up_arrow_3);
                }
            }
        });

        getScheduledList();


        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(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());
//        txtTrainingUID.setText(GlobalData.scheduledDataList.get(0).getTrainerId());
    }


    @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 void getScheduledList() {
        String scheduleID = Objects.requireNonNull(getIntent().getExtras()).getString("SCHEDULE_ID", "");
        apiService.getScheduledList(scheduleID).enqueue(new Callback<ViewScheduleListResponse>() {
            @Override
            public void onResponse(Call<ViewScheduleListResponse> call, Response<ViewScheduleListResponse> response) {
                if (response.body() != null) {
                    if (response.body().getData() != null) {
                        GlobalData.scheduledDataList = new ArrayList<>();
                        GlobalData.scheduledDataList = response.body().getData();
                        if (adapter == null) {
                            GlobalData.scheduledDataList = response.body().getData();
                            if (response.body().getData().get(0).getParticipant() != null && response.body().getData().get(0).getParticipant().size() > 0) {
                                participantList.setVisibility(View.VISIBLE);
                                txtNoDataFound.setVisibility(View.GONE);
                                adapter = new ASMParticipantListAdapter(ASMScheduleViewActivity.this, GlobalData.scheduledDataList, apiService);
                                participantList.setAdapter(adapter);
                            } else {
                                participantList.setVisibility(View.GONE);
                                txtNoDataFound.setVisibility(View.VISIBLE);
                            }
                        } else {
                            GlobalData.scheduledDataList.addAll(response.body().getData());
                            adapter.notifyDataSetChanged();
                        }
                    } else 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<ViewScheduleListResponse> call, Throwable t) {
                Log.e("rr", t.getMessage());
            }
        });
    }
}
