package com.ttiglobal.inttilectgpchat.training.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;
import com.ttiglobal.inttilectgpchat.wrappers.ScheduleResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import org.jetbrains.annotations.NotNull;

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

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

public class ScheduleListActivity extends AppCompatActivity {

    private TransparentProgressDialog progressDialog;
    private ProgressBar progressBar;
    private int PAGE = 0;
    private int TOTAL_RECORD = 0;

    private EmptyStateRecyclerView scheduleList;

    private ScheduleAdapter adapter;
    private ApiService restService;

    private List<Schedules> SCHEDULES;
    private LinearLayoutManager linearLayoutManager;
    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            mHandler.postDelayed(mRunnable, 60 * 1000);
        }
    };

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

        setContentView(R.layout.activity_schedule_list);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();
        scheduleList = findViewById(R.id.scheduleList);
        progressBar = findViewById(R.id.progressBar);

        FloatingActionButton newSchedule = findViewById(R.id.newSchedule);

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("10"))
            newSchedule.hide();

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

        linearLayoutManager = new LinearLayoutManager(ScheduleListActivity.this);
        scheduleList.setLayoutManager(linearLayoutManager);
        scheduleList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(ScheduleListActivity.this, "No schedule available", ""));
        scheduleList.setHasFixedSize(true);
        scheduleList.addOnScrollListener(recyclerViewOnScrollListener);

        try {
            if (GlobalData.user.getData().getRole().equalsIgnoreCase("10")) {
                newSchedule.hide();
            } else {
                newSchedule.show();
            }

        } catch (Exception e) {
            e.printStackTrace();
            newSchedule.hide();
        }
        newSchedule.setOnClickListener(view1 -> startActivity(new Intent(ScheduleListActivity.this, ScheduleActivity.class)));
    }

    @Override
    protected void onResume() {
        super.onResume();
        TOTAL_RECORD = 0;
        PAGE = 0;
        adapter = null;
        scheduleList.post(() -> getSchedule(true));
        Calendar calendar = Calendar.getInstance();
        int sec = calendar.get(Calendar.SECOND);
        mHandler.postDelayed(mRunnable, (60 - sec) * 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeCallbacksAndMessages(null);
    }

    private RecyclerView.OnScrollListener recyclerViewOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = linearLayoutManager.getChildCount();
            int totalItemCount = linearLayoutManager.getItemCount();
            int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();

            if (progressBar.getVisibility() != View.VISIBLE) {
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount < TOTAL_RECORD && SCHEDULES.size() < TOTAL_RECORD) {
                    PAGE++;
                    getSchedule(false);
                }
            }
        }
    };

    private void getSchedule(boolean canLoadProgress) {
        if (new UtilService().isNetworkAvailable(ScheduleListActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(ScheduleListActivity.this);
                progressDialog.show();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }

            int LIMIT = 10;
            restService.getSchedule(PAGE, LIMIT).enqueue(new Callback<ScheduleResponse>() {
                @Override
                public void onResponse(Call<ScheduleResponse> call, Response<ScheduleResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    progressBar.setVisibility(View.GONE);

                    if (response.body() != null && response.body().getStatus() == 200) {
                        TOTAL_RECORD = Integer.parseInt(response.body().getTotal());
                        if (adapter == null) {
                            SCHEDULES = response.body().getData();
                            adapter = new ScheduleAdapter(ScheduleListActivity.this, SCHEDULES, restService);
                            scheduleList.setAdapter(adapter);
                        } else {
                            SCHEDULES.addAll(response.body().getData());
                            adapter.notifyDataSetChanged();
                        }

                        if (SCHEDULES.size() == 0) {
                            scheduleList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                        } else {
                            scheduleList.invokeState(EmptyStateRecyclerView.STATE_OK);
                        }
                    } 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<ScheduleResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    progressBar.setVisibility(View.GONE);
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

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