package com.gh.gamecenter.collection;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.gh.gamecenter.common.callback.OnListClickListener;
import com.gh.gamecenter.common.constant.ItemViewType;
import com.gh.gamecenter.common.syncpage.ISyncAdapterHandler;
import com.gh.common.util.CollectionUtils;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.view.DrawableView;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.viewholder.FooterViewHolder;
import com.gh.gamecenter.common.baselist.ListAdapter;
import com.gh.gamecenter.common.baselist.LoadType;
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding;
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding;
import com.gh.gamecenter.history.ManageOption;
import com.gh.gamecenter.qa.answer.CommunityAnswerItemViewHolder;
import com.gh.gamecenter.feature.entity.AnswerEntity;
import com.gh.gamecenter.feature.entity.Questions;
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity;
import com.lightgame.utils.Utils;

import org.jetbrains.annotations.Nullable;

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

import java.util.ArrayList;

import kotlin.Pair;

/**
 * Created by khy on 22/12/17.
 */

public class AnswerAdapter extends ListAdapter<AnswerEntity> implements ISyncAdapterHandler {

    private OnListClickListener mListClickListener;

    private AnswerViewModel mListViewModel;

    private String mEntrance;

    private ManageOption mCurrentOption = ManageOption.OPTION_MANAGER;
    private PopupWindow mPopWindow;
    private PopupHistoryOptionBinding mPopupBinding;
    private ArrayList<String> selectItems = new ArrayList<>();

    public AnswerAdapter(Context context, AnswerViewModel viewModel, OnListClickListener listClickListener, String entrance) {
        super(context);
        mListViewModel = viewModel;
        mListClickListener = listClickListener;
        mEntrance = entrance;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) return ItemViewType.ITEM_FOOTER;
        return ItemViewType.ITEM_BODY;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case ItemViewType.ITEM_FOOTER:
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false);
                return new FooterViewHolder(view, mListClickListener);
            case ItemViewType.ITEM_BODY:
                view = mLayoutInflater.inflate(R.layout.community_answer_item, parent, false);
                return new CommunityAnswerItemViewHolder(CommunityAnswerItemBinding.bind(view));
            default:
                return null;
        }
    }

    public void changeOption(ManageOption option) {
        mCurrentOption = option;
        if (mCurrentOption == ManageOption.OPTION_MANAGER) {
            if (mPopWindow != null) {
                selectItems.clear();
                mPopWindow.dismiss();
                mPopWindow = null;
            }
        } else {
            if (mPopWindow == null || mPopWindow.isShowing()) {
                showOptionWindow();
            }
        }

        notifyItemRangeChanged(0, mEntityList.size());
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case ItemViewType.ITEM_BODY:
                CommunityAnswerItemViewHolder viewHolder = (CommunityAnswerItemViewHolder) holder;
                AnswerEntity entity = mEntityList.get(position);
                String path;
                if (AnswerFragment.COLLECTION.equals(mListViewModel.getType())) {
                    path = "我的收藏-回答列表";
                } else if (AnswerFragment.HISTORY.equals(mListViewModel.getType())) {
                    path = "浏览记录-回答列表";
                    viewHolder.itemView.setOnLongClickListener(v -> {
                        DialogHelper.showDialog(holder.itemView.getContext(),
                                "删除记录",
                                "删除浏览记录将不可恢复，确定删除吗？",
                                "确定",
                                "取消",
                                () -> {
                                    mListViewModel.removeHistory(entity);
                                },
                                () -> {
                                },
                                false, "", "");
                        return false;
                    });
                } else {
                    path = "插入回答-收藏回答列表";
                }
                viewHolder.getBinding().imageContainer.setOffset(mCurrentOption == ManageOption.OPTION_MANAGER ? 40f : 76f);
                viewHolder.bindAnswerItem(entity, mEntrance, path);

                viewHolder.getBinding().selectIv.setVisibility(mCurrentOption == ManageOption.OPTION_MANAGER ? View.GONE : View.VISIBLE);
                viewHolder.getBinding().selectIv.setChecked(selectItems.contains(entity.getId()));

                holder.itemView.setOnClickListener(v -> {
                    if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                        if (entity.getActive()) {
                            mContext.startActivity(NewQuestionDetailActivity.getCommentIntent(mContext, entity.getQuestions().getId(), entity.getId(), mEntrance, path));
                        } else {
                            showDeleteDialog(entity.getId());
                        }

                        if (!entity.getRead()) {
                            entity.setRead(true);
                            notifyItemChanged(position);
                            mListViewModel.postCollectionAnswerRead(entity.getId());
                        }
                    } else {
                        if (selectItems.contains(entity.getId())) {
                            selectItems.remove(entity.getId());
                        } else {
                            selectItems.add(entity.getId());
                        }
                        checkSelectItems();
                        notifyItemChanged(position);
                    }
                });
                viewHolder.getBinding().title.setOnClickListener(v -> {
                    if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                        Questions questions = entity.getQuestions();
                        mContext.startActivity(NewQuestionDetailActivity.getIntent(mContext, questions.getId(), mEntrance, path));
                    }
                });
                break;
            case ItemViewType.ITEM_FOOTER:
                FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
                footerViewHolder.initItemPadding();
                footerViewHolder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver);
                break;
        }
    }

    private void showDeleteDialog(String answerId) {
        DialogHelper.showCenterDialog(mContext, "提示"
                , "内容已被删除，是否取消收藏？"
                , "取消收藏", "暂不"
                , () -> CollectionUtils.INSTANCE.deleteCollection(answerId
                        , CollectionUtils.CollectionType.ANSWER, new CollectionUtils.OnCollectionListener() {
                            @Override
                            public void onSuccess() {
                                Utils.toast(mContext, R.string.collection_cancel);
                                mListViewModel.load(LoadType.REFRESH);
                            }

                            @Override
                            public void onError() {
                                Utils.toast(mContext, R.string.collection_cancel_failure);
                            }
                        }), () -> {
                });
    }


    @Override
    public int getItemCount() {
        return mEntityList == null || mEntityList.isEmpty() ? 0 : mEntityList.size() + FOOTER_ITEM_COUNT;
    }

    @Nullable
    @Override
    public Pair<String, Object> getSyncData(int position) {
        if (position >= mEntityList.size()) return null;
        AnswerEntity entity = mEntityList.get(position);
        return new Pair(entity.getId(), entity);
    }

    private void showOptionWindow() {
        mPopupBinding = PopupHistoryOptionBinding.inflate(LayoutInflater.from(mContext));
        mPopupBinding.getRoot().setFocusable(true);
        mPopupBinding.getRoot().setFocusableInTouchMode(true);

        mPopWindow = new PopupWindow(mPopupBinding.getRoot(), LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtils.dip2px(56f));
        mPopWindow.showAtLocation(((AppCompatActivity) mContext).getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        mPopupBinding.itemDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelper.showDialog(mContext,
                        "是否删除" + selectItems.size() + "条记录？",
                        "提示：删除记录将不可恢复",
                        "删除",
                        "取消",
                        () -> {
                            mListViewModel.removeHistories(selectItems);
                            selectItems.clear();
                            checkSelectItems();
                        },
                        () -> {
                        },
                        false, "", "");


            }
        });
        mPopupBinding.checkAllCb.setCompoundDrawablesWithIntrinsicBounds(
                DrawableView.getCheckSelectorDrawable(
                        mContext
                ), null, null, null
        );
        mPopupBinding.checkAllCb.setOnClickListener(v -> {
            if (mPopupBinding.checkAllCb.isChecked()) {
                selectItems.clear();
                for (AnswerEntity entity : mEntityList) {
                    selectItems.add(entity.getId());
                }
            } else {
                selectItems.clear();
            }
            checkSelectItems();
            notifyItemRangeChanged(0, mEntityList.size());
        });
        checkSelectItems();
    }

    private void checkSelectItems() {
        if (mPopupBinding == null) return;
        mPopupBinding.selectNumTv.setText(selectItems.isEmpty() ? "" : "(" + selectItems.size() + ")");
        mPopupBinding.itemDelete.setBackground(selectItems.isEmpty() ? ExtensionsKt.toDrawable(R.drawable.bg_shape_f5_radius_999) : ExtensionsKt.toDrawable(R.drawable.download_button_normal_style));
        mPopupBinding.itemDelete.setTextColor(selectItems.isEmpty() ? ExtensionsKt.toColor(R.color.text_body) : ExtensionsKt.toColor(R.color.white));
        mPopupBinding.itemDelete.setEnabled(!selectItems.isEmpty());
        mPopupBinding.checkAllCb.setChecked(selectItems.size() == mEntityList.size());
    }
}
