package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.cygnusa.hyperm.fragments.ReviewFragment;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CustomViewPager;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
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.AssessmentList;
import com.cygnusa.hyperm.wrappers.AssessmentScore;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.ReviewQuestion;
import com.cygnusa.hyperm.wrappers.ReviewResponse;

import java.util.ArrayList;

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


public class ReviewActivity extends AppCompatActivity {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView title;
    public static AssessmentList ASSESSMENT = new AssessmentList();
    public static AssessmentScore ASSESSMENT_SCORE = new AssessmentScore();

    ArrayList<ReviewQuestion> REVIEW_QUESTIONS = new ArrayList<>();
    CustomViewPager viewPager;
    SmartTabLayout indicatorTab;
    ImageButton previous, next;


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

        setContentView(R.layout.activity_review);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        viewPager = findViewById(R.id.viewPager);
        indicatorTab = findViewById(R.id.indicatorTab);
        previous = findViewById(R.id.previous);
        next = findViewById(R.id.next);
        title.setText(ASSESSMENT.getAssessmentname());
        title.setSelected(true);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        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);

        viewPager.post(new Runnable() {
            @Override
            public void run() {
                getReviewQuistion();
            }
        });

        previous.setEnabled(false);
        next.setEnabled(false);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    previous.setEnabled(false);
                    next.setEnabled(true);
                } else if (position == REVIEW_QUESTIONS.size() - 1) {
                    previous.setEnabled(true);
                    next.setEnabled(false);
                    ReviewFragment.submitButton.setVisibility(View.VISIBLE);
                } else {
                    previous.setEnabled(true);
                    next.setEnabled(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() > 0) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() < REVIEW_QUESTIONS.size() - 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                }
            }
        });

    }

    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();
            ReviewActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }


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

    private void getReviewQuistion() {
        if (new UtilService().isNetworkAvailable(ReviewActivity.this)) {
            progressDialog = new TransparentProgressDialog(ReviewActivity.this);
            progressDialog.show();

            restService.getReviewQuistion(ASSESSMENT_SCORE.getResult_id()).enqueue(new Callback<ReviewResponse>() {
                @Override
                public void onResponse(Call<ReviewResponse> call, Response<ReviewResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    if (response.body() != null && response.body().getStatus() == 200) {
                        REVIEW_QUESTIONS = response.body().getData();
                        setReviewQuistion();
                    } 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<ReviewResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    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 setReviewQuistion() {
        viewPager.setPageTransformer(true, new DepthPageTransformerNew());
        viewPager.setAdapter(new ReviewQuistionAdapter(getSupportFragmentManager()));
        indicatorTab.setViewPager(viewPager);
        viewPager.setPagingEnabled(true);
        if (REVIEW_QUESTIONS.size() > 0) {
            previous.setEnabled(false);
            next.setEnabled(true);
            if (REVIEW_QUESTIONS.size() == 1) {
                ReviewFragment.submitButton.setVisibility(View.VISIBLE);
            }
        }
        viewPager.setOffscreenPageLimit(REVIEW_QUESTIONS.size());
    }


    public class ReviewQuistionAdapter extends FragmentStatePagerAdapter {

        private ReviewQuistionAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            ReviewFragment fragment = new ReviewFragment();
            fragment.setReviewQuestion(getApplicationContext(), REVIEW_QUESTIONS.get(position));
            fragment.setQuestionNo(String.valueOf((position + 1)));
            return fragment;
        }

        @Override
        public int getCount() {
            return REVIEW_QUESTIONS.size();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return String.valueOf((position + 1));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            finish();
        }
    }
}