package io.openim.android.ouicontact.ui.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;

import java.util.List;

import io.openim.android.ouicontact.R;
import io.openim.android.ouicontact.databinding.ActivitySerchGroupBinding;
import io.openim.android.ouicontact.vm.SearchGroup;
import io.openim.android.ouicore.adapter.RecyclerViewAdapter;
import io.openim.android.ouicore.adapter.ViewHol;
import io.openim.android.ouicore.base.BaseActivity;
import io.openim.android.ouicore.base.BaseApp;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.Routes;
import io.openim.android.ouicore.widget.HeaderAndFooterWrapper;
import io.openim.android.ouicore.widget.StickyDecoration;
import io.openim.android.sdk.models.GroupInfo;

/**
 * 搜索群组
 */
public class SearchGroupActivity extends BaseActivity<SearchGroup, ActivitySerchGroupBinding> {

    private ContentAdapter adapter;
    private Handler handler = new Handler();
    private LinearLayout bottomLayout;
    private TextView itemCount;
    private HeaderAndFooterWrapper headerAndFooterWrapper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        bindVMByCache(SearchGroup.class);
        super.onCreate(savedInstanceState);
        bindViewDataBinding(ActivitySerchGroupBinding.inflate(getLayoutInflater()));
        sink();
        initView();
        listener();
    }

    private void listener() {
        vm.searchGroups.observe(this, groupInfos -> {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (bottomLayout != null) {
                        bottomLayout.setVisibility(groupInfos.isEmpty() ? View.GONE : View.VISIBLE);
                    }
                    if (itemCount != null) {
                        itemCount.setText(String.format(StringUtils.getString(io.openim.android.ouicore.R.string.a_total_of_groups), groupInfos.size()));
                    }
                    adapter.setItems(groupInfos);
                    headerAndFooterWrapper.notifyDataSetChanged();
                }
            });


        });
        vm.searchKey.observe(this, s -> {
            vm.search(s);
        });
        view.searchView.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) vm.searchKey.setValue("");
            }

            @Override
            public void afterTextChanged(Editable s) {
                handler.removeCallbacksAndMessages(null);
                handler.postDelayed(() -> {
                    String input = s.toString();
                    vm.searchKey.setValue(input);
                }, 300);
            }
        });
    }

    private void initView() {
        view.searchView.getEditText().setHint(io.openim.android.ouicore.R.string.search_group);
        view.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContentAdapter(ViewHol.GroupViewHo.class);
        headerAndFooterWrapper = new HeaderAndFooterWrapper(adapter);
        headerAndFooterWrapper.addFooterView(bottomLayout());
        view.recyclerview.setAdapter(headerAndFooterWrapper);
        view.recyclerview.addItemDecoration(new StickyDecoration(this,
                position -> {
                    LogUtils.e(position + "---" + headerAndFooterWrapper.getItemCount());
                    if (position + 1 == headerAndFooterWrapper.getItemCount()) {
                        return "";
                    }
                    int pos = position;
                    String str = adapter.getItems().get(pos).groupType;
                    return str;
                }));
    }

    private View bottomLayout() {
        View top = LayoutInflater.from(this).inflate(R.layout.view_seach_group_bottom, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ConvertUtils.dp2px(68));
        top.setLayoutParams(params);
        bottomLayout = top.findViewById(R.id.layout);
        itemCount = top.findViewById(R.id.count);
        return top;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeCacheVM();
    }

    public static void jumpThis(Context ctx, List<GroupInfo> groupInfos) {
        SearchGroup searchGroup = new SearchGroup();
        searchGroup.groups.setValue(groupInfos);
        BaseApp.inst().putVM(searchGroup);
        ctx.startActivity(new Intent(ctx, SearchGroupActivity.class));
    }

    public class ContentAdapter extends RecyclerViewAdapter<GroupInfoExpand, ViewHol.GroupViewHo> {

        public ContentAdapter(Class<ViewHol.GroupViewHo> viewHolder) {
            super(viewHolder);
        }

        @Override
        public void onBindView(@NonNull ViewHol.GroupViewHo holder, GroupInfoExpand data, int position) {
            holder.view.avatar.load(data.getFaceURL(), true);
            holder.view.title.setText(data.getGroupName());
            holder.view.description.setText(data.getMemberCount() + SearchGroupActivity.this.getString(io.openim.android.ouicore.R.string.people));

            holder.view.getRoot().setOnClickListener(v -> {
                ARouter.getInstance().build(Routes.Conversation.CHAT).withString(Constants.K_GROUP_ID, data.getGroupID()).withString(Constants.K_NAME, data.getGroupName()).navigation();
            });
        }
    }
}
