package co.pixelbeard.theanfieldwrap.writing;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.loopeer.shadow.ShadowView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.Article;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.home.HomeFragmentListener;
import co.pixelbeard.theanfieldwrap.networking.NetworkConstants;
import co.pixelbeard.theanfieldwrap.playerService.MediaPlayerInterface;
import co.pixelbeard.theanfieldwrap.playerService.PodcastStorageUtil;
import co.pixelbeard.theanfieldwrap.utils.AnimUtils;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.ScreenUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import io.realm.Realm;

public class WritingFragment extends BaseFragment implements WritingContract.View {

    private static final String TAG = WritingFragment.class.getSimpleName() + "(FEED)";

    @BindView(R.id.sv_toolbar)
    ShadowView svToolbar;
    @BindView(R.id.img_writing_header)
    ImageView imgWritingHeader;
    @BindView(R.id.img_taw_logo)
    ImageView imgTawLogo;
    @BindView(R.id.txt_writing_title)
    TextView txtWritingTitle;

    @BindView(R.id.srl_writing)
    SwipeRefreshLayout srlWriting;
    @BindView(R.id.rv_writing)
    RecyclerView rvWriting;

    @BindView(R.id.ll_writing_no_connection)
    LinearLayout llWritingNoConnection;
    @BindView(R.id.txt_no_connection_title)
    TextView txtNoConnectionTitle;
    @BindView(R.id.txt_no_connection_body)
    TextView txtNoConnectionBody;

    @BindView(R.id.ll_writing_lazy_loader)
    LinearLayout llWritingLazyLoader;


    private Context mContext;
    private HomeFragmentListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;

    private WritingAdapter adapter;

    private WritingContract.Presenter mPresenter;

    private int mCurrentPage = 1;
    private boolean isLastPage = false;

    public WritingFragment() {
        // Required empty public constructor
    }

    public static WritingFragment newInstance() {
        WritingFragment fragment = new WritingFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mContext = context;
        mListener = (HomeFragmentListener) context;
        mediaPlayerInterface = (MediaPlayerInterface) context;
    }

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

        new WritingPresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_writing, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setTextViewFont();
        setRecyclerViewLayoutManager();

        setScrollViewListener();
        setSwipeRefreshListener();

        if (adapter == null) {
            mCurrentPage = 1;
            mPresenter.checkUserSubs();
            mPresenter.subscribe();
        } else {
            rvWriting.setAdapter(adapter);
            new Handler().postDelayed(this::showUi, 200);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.unsubscribe();
    }

    private void setTextViewFont() {
        txtWritingTitle.setTypeface(FontUtils.getInstance().getDinProBlack());

        txtNoConnectionTitle.setTypeface(FontUtils.getInstance().getDinProBlack());
        txtNoConnectionBody.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setRecyclerViewLayoutManager() {
        rvWriting.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
    }

    private void setScrollViewListener() {


        float startOffset = ScreenUtils.dpToPx(20, mContext);
        float maxOffset = ScreenUtils.dpToPx(20, mContext);


        rvWriting.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    recyclerView.stopScroll();
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int scrollY = recyclerView.computeVerticalScrollOffset();

                int visibleItemCount = recyclerView.getLayoutManager().getChildCount();
                int totalItemCount = recyclerView.getLayoutManager().getItemCount();
                int pastVisibleItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();

                if ((visibleItemCount + pastVisibleItems) >= totalItemCount && !adapter.isRefreshing() && !isLastPage) {
//                    srlWriting.setRefreshing(true);
                    adapter.addLoader();
                    mPresenter.getArticles(mCurrentPage);
                }

                float percent = (scrollY - maxOffset) / 100;

                svToolbar.setAlpha(percent);
                imgWritingHeader.setAlpha(1 - percent);
                imgTawLogo.setAlpha(1 - percent);

                imgWritingHeader.setTranslationY((float) -(scrollY * 3));
                imgTawLogo.setTranslationY((float) -(scrollY * 3.5));

                if ((float) scrollY >= startOffset) {
                    svToolbar.setVisibility(View.VISIBLE);
                } else {
                    svToolbar.setVisibility(View.GONE);
                }
            }
        });
    }

    private void setSwipeRefreshListener() {
        srlWriting.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.red801812));

        srlWriting.setProgressViewOffset(false, 0, (int) ScreenUtils.dpToPx(80, mContext));
        srlWriting.setOnRefreshListener(() -> {
            mCurrentPage = 1;
            mPresenter.refreshArticles();
        });
    }

    @Override
    public void setWritingAdapter(List<Article> articles, Article featuredArticle) {
        if (mCurrentPage == 1) {
            isLastPage = false;
            adapter = null;
        } else if (articles.size() < NetworkConstants.PAGE_SIZE) {
            isLastPage = true;
        }


        if (adapter == null) {
            if (isAdded()) {
                adapter = new WritingAdapter(articles, featuredArticle, article -> mListener.setWritingDetailsFrag(article));
                rvWriting.setAdapter(adapter);
            }
        } else {
            adapter.add(articles);
        }
        mCurrentPage++;
    }

    @Override
    public void showNoConnectionUi() {
        if (isAdded()) {
            llWritingNoConnection.setVisibility(View.VISIBLE);
            llWritingLazyLoader.setVisibility(View.GONE);
        }
    }

    @Override
    public void showNoConnectionHeader() {
        if (mListener != null && isAdded()) {
            mListener.showNoInternetHeader();
        }
    }

    @Override
    public void showUi() {
        llWritingNoConnection.setVisibility(View.GONE);
        new Handler().postDelayed(() -> {
            if (isAdded() && !isDetached()) {
                AnimUtils.startTranslateAlphaEntryAnimationSet(rvWriting, ScreenUtils.dpToPx(50, mContext), 0, null);
            }
        }, 50);
    }

    @Override
    public void setSwipeRefreshRefreshing(boolean refreshing) {
        if (srlWriting.isRefreshing() == !refreshing && isAdded()) {
            srlWriting.setRefreshing(refreshing);
        }
    }

    @Override
    public void showSingleButtonDialog(String error, String message) {
        if (mListener != null)
            mListener.showSingleButtonDialog(error, message, null);
    }

    @Override
    public void setPresenter(WritingContract.Presenter presenter) {
        if (presenter != null) {
            mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        if (mListener != null && isAdded()) {
            mListener.goBack();
        }
    }

    @Override
    public void showLoader(String text) {
        if (!srlWriting.isRefreshing() && mCurrentPage == 1 && isAdded()) {
            llWritingNoConnection.setVisibility(View.GONE);
            llWritingLazyLoader.setVisibility(View.VISIBLE);
            llWritingLazyLoader.startAnimation(AnimUtils.getPulsateFade(mContext));
        }
    }

    @Override
    public void hideLoader() {
        if (isAdded()) {
            llWritingLazyLoader.clearAnimation();
            llWritingLazyLoader.setVisibility(View.GONE);

            if (srlWriting.isRefreshing()) {
                srlWriting.setRefreshing(false);
            }
        }
    }

    @Override
    public void onUnknownError(String error) {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.error), error, null);
        }
    }

    @Override
    public void onTimeout() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body), null);
        }
    }

    @Override
    public void onNetworkError() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body), null);
        }
    }

    @Override
    public void onConnectionError() {
        if (mCurrentPage == 1) {
            showNoConnectionUi();
            hideLoader();
        } else {
            showNoConnectionHeader();
            setSwipeRefreshRefreshing(false);
        }
    }

    @Override
    public void logoutUser() {
        mPresenter.clearUserData(mContext);
        if (mediaPlayerInterface.isPlaying()) {
            mediaPlayerInterface.stop();
        }
        PodcastStorageUtil.getInstance().clearStoredPodcast();
        mListener.startWalkThroughActivity();
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(mContext);
    }

}
