package co.pixelbeard.theanfieldwrap.videos;


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.Video;
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 VideosFragment extends BaseFragment implements VideosContract.View {

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

    //Toolbar UI
    @BindView(R.id.sv_toolbar)
    ShadowView svToolbar;

    @BindView(R.id.img_videos_header)
    ImageView imgVideosHeader;

    @BindView(R.id.img_taw_logo)
    ImageView imgTawLogo;


    //Main UI
    @BindView(R.id.srl_videos)
    SwipeRefreshLayout srlVideos;

    @BindView(R.id.rv_videos)
    RecyclerView rvVideos;

    @BindView(R.id.ll_video_lazy_loader)
    LinearLayout llVideoLazyLoader;

    @BindView(R.id.txt_videos_title)
    TextView txtVideosTitle;

    //No Connection UI
    @BindView(R.id.ll_video_no_connection)
    LinearLayout llVideoNoConnection;
    @BindView(R.id.txt_no_connection_title)
    TextView txtNoConnectionTitle;
    @BindView(R.id.txt_no_connection_body)
    TextView txtNoConnectionBody;

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


    private VideosAdapter adapter;

    private VideosContract.Presenter mPresenter;


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

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

    public static VideosFragment newInstance() {
        VideosFragment fragment = new VideosFragment();
        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 VideosPresenter(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_videos, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

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

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

    @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 {
            rvVideos.setAdapter(adapter);
            new Handler().postDelayed(this::showUi, 200);
        }

    }

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

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

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

    }

    private void setScrollViewListener() {

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


        rvVideos.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) {
                    adapter.addLoader();
                    mPresenter.getVideos(mCurrentPage);
                }

                float percent = (scrollY - maxOffset) / 100;

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

                imgVideosHeader.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() {
        srlVideos.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.red801812));

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

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

    @Override
    public void goBack() {
        mListener.goBack();
    }

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

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

            if (srlVideos.isRefreshing()) {
                srlVideos.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);
    }

    @Override
    public void setVideosAdapter(List<Video> videos) {

        if (videos == null) {
            return;
        }

        if (mCurrentPage == 1) {
            isLastPage = false;
            adapter = null;
        } else if (videos.size() < NetworkConstants.PAGE_SIZE) {
            isLastPage = true;
        }

        if (adapter == null) {
            adapter = new VideosAdapter(videos, video -> mListener.setVideoDetailsFrag(video));
            if (isAdded()) {
                rvVideos.setAdapter(adapter);
            }
        } else {
            adapter.add(videos);
        }
        mCurrentPage++;
        if (srlVideos.isRefreshing()) {
            srlVideos.setRefreshing(false);
        }
    }

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

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

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

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

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