package com.app.intelligent.board.uiactivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ad.tradpluslibrary.TPAdManager;
import com.app.intelligent.board.AppContextHelper;
import com.app.intelligent.board.R;
import com.app.intelligent.board.databinding.ActivitySearchBinding;
import com.app.intelligent.board.databinding.AdapterHomeItemSubBinding;
import com.app.intelligent.board.databinding.LayoutSearchHistoryBinding;
import com.app.intelligent.board.databinding.LayoutSearchTrendingBinding;
import com.app.intelligent.board.databinding.ItemSearchHistoryBinding;
import com.app.intelligent.board.databinding.ItemSearchTagSingleBinding;
import com.app.intelligent.board.uimodel.KeyboardItemInfo;
import com.app.intelligent.board.uimodel.KeyboardItemDataWrapper;
import com.app.intelligent.board.utils.AppCommonUtils;
import com.app.intelligent.board.utils.KeyboardRvItemDecoration;
import com.bumptech.glide.Glide;
import java.util.HashSet;
import java.util.Set;

public class SearchActivity extends AppCompatActivity {
    private ActivitySearchBinding vb;
    private FrameLayout flContent;

    // 历史记录核心配置
    private LayoutSearchHistoryBinding historyBinding;
    private List<String> historyList = new ArrayList<>();
    private HistoryAdapter historyAdapter;
    private static final String SP_NAME = "search_history_sp";
    private static final String KEY_HISTORY_STR = "history_str";
    private static final int MAX_HISTORY_COUNT = 6;
    private static final String SEPARATOR = "|";

    // Trending相关
    private LayoutSearchTrendingBinding trendingBinding;
    private List<KeyboardItemInfo> trendingList = new ArrayList<>();
    private TrendingAdapter trendingAdapter;

    // 联想词相关
    private RecyclerView tagRv;
    private TagAdapter tagAdapter;
    private List<String> matchedTags = new ArrayList<>();

    // 搜索结果相关
    private RecyclerView resultRv;
    private ResultAdapter resultAdapter;
    private List<KeyboardItemInfo> resultList = new ArrayList<>();
    // 无结果页面View
    private View noResultView;

    // 固定尺寸常量
    private static final int KEYBOARD_ITEM_HEIGHT = 240; // dp

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

        vb = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(vb.getRoot());
        flContent = vb.flContent;
        // 系统栏Insets适配
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化无结果页面View
        initNoResultView();
        // 初始化View
        initHistoryView();
        initTrendingView();
        initTagView();
        initResultView();

        // 初始化数据
        initHistoryRecord();
        initTrendingData();

        // 初始显示
        showInitialView();

        // 初始化监听
        initListeners();

        // 激活搜索框+弹出键盘
        vb.etSearch.requestFocus();
        showSoftInputForce();
    }

    // ====================== 无结果页面初始化 ======================
    private void initNoResultView() {
        // 创建无结果页面布局
        noResultView = LayoutInflater.from(this).inflate(R.layout.layout_no_search_result, null);
        noResultView.setLayoutParams(new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
        ));
        // 可选：设置无结果提示文字（也可以直接在xml中写死）
        TextView tvTip = noResultView.findViewById(R.id.tv_no_result_tip);
        tvTip.setText("No relevant content found");
    }

    // ====================== 历史记录相关 ======================
    private void initHistoryView() {
        historyBinding = LayoutSearchHistoryBinding.inflate(getLayoutInflater());
        historyAdapter = new HistoryAdapter(historyList);
        historyBinding.rvHistoryList.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        historyBinding.rvHistoryList.setAdapter(historyAdapter);
        historyBinding.rvHistoryList.setNestedScrollingEnabled(false);

        historyBinding.tvClearAll.setOnClickListener(v -> {
            historyList.clear();
            saveHistoryToSP();
            updateHistoryView();
        });
    }

    private void initHistoryRecord() {
        SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE);
        String historyStr = sp.getString(KEY_HISTORY_STR, "");
        historyList.clear();

        if (!historyStr.isEmpty()) {
            String[] historyArray = historyStr.split("\\" + SEPARATOR);
            for (String keyword : historyArray) {
                if (!keyword.isEmpty()) {
                    historyList.add(keyword);
                }
            }
        }

        if (historyList.size() > MAX_HISTORY_COUNT) {
            historyList = historyList.subList(0, MAX_HISTORY_COUNT);
            saveHistoryToSP();
        }

        updateHistoryView();
    }

    private void updateHistoryView() {
        if (historyList.isEmpty()) {
            historyBinding.rvHistoryList.setVisibility(View.GONE);
            historyBinding.tvNoHistory.setVisibility(View.VISIBLE);
            historyBinding.tvClearAll.setVisibility(View.GONE);
        } else {
            historyBinding.rvHistoryList.setVisibility(View.VISIBLE);
            historyBinding.tvNoHistory.setVisibility(View.GONE);
            historyBinding.tvClearAll.setVisibility(View.VISIBLE);
            historyAdapter.notifyDataSetChanged();
        }
    }

    private void saveHistoryToSP() {
        SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < historyList.size(); i++) {
            sb.append(historyList.get(i));
            if (i < historyList.size() - 1) {
                sb.append(SEPARATOR);
            }
        }

        editor.putString(KEY_HISTORY_STR, sb.toString()).apply();
    }

    private void addToHistory(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) return;
        String trimKeyword = keyword.trim();

        historyList.remove(trimKeyword);
        historyList.add(0, trimKeyword);

        if (historyList.size() > MAX_HISTORY_COUNT) {
            historyList.remove(historyList.size() - 1);
        }

        saveHistoryToSP();
        updateHistoryView();
    }

    // ====================== Trending相关 ======================
    private void initTrendingView() {
        trendingBinding = LayoutSearchTrendingBinding.inflate(getLayoutInflater());
        trendingAdapter = new TrendingAdapter(trendingList, this);

        trendingBinding.rvTrending.setLayoutManager(new GridLayoutManager(this, 1) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                RecyclerView.LayoutParams params = super.generateDefaultLayoutParams();
                int targetHeight = (int) (KEYBOARD_ITEM_HEIGHT * getResources().getDisplayMetrics().density);
                params.height = targetHeight;
                return params;
            }
        });

        trendingBinding.rvTrending.setAdapter(trendingAdapter);
        trendingBinding.rvTrending.setNestedScrollingEnabled(false);

        KeyboardRvItemDecoration listDecoration = new KeyboardRvItemDecoration(15, 15, 0);
        if (trendingBinding.rvTrending.getItemDecorationCount() == 0) {
            trendingBinding.rvTrending.addItemDecoration(listDecoration);
        }

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        trendingBinding.rvTrending.setLayoutParams(params);
    }

    private void initTrendingData() {
        trendingList.clear();
        if (AppContextHelper.trendingKeyboards == null) {
            AppContextHelper.trendingKeyboards = new ArrayList<>();
        }

        if (AppContextHelper.trendingKeyboards.isEmpty()) {
            List<KeyboardItemInfo> allKeyboards = new ArrayList<>();
            Set<String> allKeyboardIdSet = new HashSet<>();

            if (AppContextHelper.list != null && !AppContextHelper.list.isEmpty()) {
                for (KeyboardItemDataWrapper wrapper : AppContextHelper.list) {
                    if (wrapper == null || wrapper.getKeyboardList() == null) continue;
                    for (KeyboardItemInfo keyboard : wrapper.getKeyboardList()) {
                        if (keyboard != null && keyboard.getTitleName() != null) {
                            String uniqueKey = keyboard.getTitleName();
                            if (!allKeyboardIdSet.contains(uniqueKey)) {
                                allKeyboardIdSet.add(uniqueKey);
                                allKeyboards.add(keyboard);
                            }
                        }
                    }
                }
            }

            if (allKeyboards.isEmpty()) {
                for (int i = 0; i < 8; i++) {
                    KeyboardItemInfo testInfo = new KeyboardItemInfo();
                    testInfo.setTitleName("Test Keyboard " + (i+1));
                    testInfo.setThumbUrl("https://example.com/keyboard_" + (i+1) + ".png");
                    allKeyboards.add(testInfo);
                }
            }

            Random random = new Random();
            Set<Integer> selectedIndexes = new HashSet<>();
            int needCount = Math.min(8, allKeyboards.size());
            while (selectedIndexes.size() < needCount) {
                selectedIndexes.add(random.nextInt(allKeyboards.size()));
            }

            AppContextHelper.trendingKeyboards.clear();
            for (int index : selectedIndexes) {
                AppContextHelper.trendingKeyboards.add(allKeyboards.get(index));
            }
        }

        trendingList.addAll(AppContextHelper.trendingKeyboards);
        trendingAdapter.notifyDataSetChanged();
        trendingBinding.rvTrending.setVisibility(View.VISIBLE);
    }

    // ====================== 联想词View初始化 ======================
    private void initTagView() {
        tagRv = new RecyclerView(this);
        tagAdapter = new TagAdapter(matchedTags);
        tagRv.setLayoutManager(new LinearLayoutManager(this));
        tagRv.setLayoutParams(new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
        ));
        tagRv.setBackgroundResource(R.drawable.shape_search_tag_container);
        tagRv.setPadding(dp2px(12), dp2px(12), dp2px(12), dp2px(12));
        tagRv.setClipToPadding(true);
        tagRv.setAdapter(tagAdapter);
    }

    // ====================== 搜索结果View初始化 ======================
    private void initResultView() {
        resultRv = new RecyclerView(this);
        resultAdapter = new ResultAdapter(resultList, this);

        resultRv.setLayoutManager(new GridLayoutManager(this, 1) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                RecyclerView.LayoutParams params = super.generateDefaultLayoutParams();
                int targetHeight = (int) (KEYBOARD_ITEM_HEIGHT * getResources().getDisplayMetrics().density);
                params.height = targetHeight;
                return params;
            }
        });

        resultRv.setLayoutParams(new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
        ));

        KeyboardRvItemDecoration listDecoration = new KeyboardRvItemDecoration(15, 15, 0);
        if (resultRv.getItemDecorationCount() == 0) {
            resultRv.addItemDecoration(listDecoration);
        }

        resultRv.setAdapter(resultAdapter);
        resultRv.setNestedScrollingEnabled(false);
    }

    // ====================== 视图切换逻辑 ======================
    private void showInitialView() {
        flContent.removeAllViews();
        LinearLayout container = new LinearLayout(this);
        container.setOrientation(LinearLayout.VERTICAL);
        container.setLayoutParams(new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
        ));

        removeViewFromParent(historyBinding.getRoot());
        removeViewFromParent(trendingBinding.getRoot());

        container.addView(historyBinding.getRoot());
        container.addView(trendingBinding.getRoot());

        flContent.addView(container);
    }

    private void showTagView() {
        flContent.removeAllViews();
        flContent.addView(tagRv);
        tagAdapter.notifyDataSetChanged();
    }

    private void showResultView() {
        flContent.removeAllViews();
        // 无结果显示无结果页面，有结果显示列表
        if (resultList.isEmpty()) {
            flContent.addView(noResultView);
        } else {
            TPAdManager.INSTANCE.showTPAD(this,()-> {
                flContent.addView(resultRv);
                return null;
            });

        }
    }

    private void removeViewFromParent(View view) {
        if (view.getParent() != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
    }

    // ====================== 数据加载逻辑 ======================
    private void matchTags(String key) {
        matchedTags.clear();
        Set<String> titleSet = new HashSet<>();

        if (AppContextHelper.list != null) {
            for (KeyboardItemDataWrapper wrapper : AppContextHelper.list) {
                if (wrapper == null || wrapper.getKeyboardList() == null) continue;
                for (KeyboardItemInfo keyboard : wrapper.getKeyboardList()) {
                    if (keyboard != null && keyboard.getTitleName() != null
                            && keyboard.getTitleName().toLowerCase().contains(key.toLowerCase())
                            && !titleSet.contains(keyboard.getTitleName())) {
                        titleSet.add(keyboard.getTitleName());
                        matchedTags.add(keyboard.getTitleName());
                    }
                }
            }
        }
    }

    private void searchKeyboards(String key) {
        resultList.clear();
        if (AppContextHelper.list == null) return;

        Set<String> keyboardIdSet = new HashSet<>();
        for (KeyboardItemDataWrapper wrapper : AppContextHelper.list) {
            if (wrapper == null || wrapper.getKeyboardList() == null) continue;
            for (KeyboardItemInfo keyboard : wrapper.getKeyboardList()) {
                if (keyboard != null
                        && keyboard.getTitleName() != null
                        && keyboard.getTitleName().toLowerCase().contains(key.toLowerCase())) {

                    String uniqueKey = keyboard.getTitleName();
                    if (!keyboardIdSet.contains(uniqueKey)) {
                        keyboardIdSet.add(uniqueKey);
                        resultList.add(keyboard);
                    }
                }
            }
        }
        resultAdapter.notifyDataSetChanged();
    }

    // ====================== 监听事件 ======================
    private void initListeners() {
        // 返回按钮点击事件
        vb.ivBack.setOnClickListener(v ->   TPAdManager.INSTANCE.showTPAD(this,()->{
            finish();
            return null;
        })
        );

        // 软键盘搜索按钮拦截
        vb.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String key = vb.etSearch.getText().toString().trim();
                if (!key.isEmpty()) {
                    addToHistory(key);
                    searchKeyboards(key);
                    showResultView();
                    hideSoftInput();
                }
                return true;
            }
            return false;
        });

        vb.etSearch.addTextChangedListener(new TextWatcher() {
            private String lastKey = "";
            private boolean isSwitching = false;

            @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 (isSwitching) return;
                String key = s.toString().trim();
                if (key.equals(lastKey)) return;
                lastKey = key;

                matchedTags.clear();

                if (!key.isEmpty()) {
                    matchTags(key);
                    isSwitching = true;
                    if (matchedTags.isEmpty()) {
                        searchKeyboards(key);
                        showResultView();
                    } else {
                        showTagView();
                    }
                    isSwitching = false;
                } else {
                    vb.etSearch.postDelayed(() -> {
                        isSwitching = true;
                        showInitialView();
                        resultList.clear();
                        resultAdapter.notifyDataSetChanged();
                        isSwitching = false;
                    }, 100);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 搜索按钮点击事件
        vb.ivSearchBtn.setOnClickListener(v -> {
            String key = vb.etSearch.getText().toString().trim();
            if (key.isEmpty()) {
                vb.etSearch.setError("Enter search keywords");
                return;
            }

            addToHistory(key);
            searchKeyboards(key);
            showResultView();
            hideSoftInput();
        });
    }

    // ====================== 工具方法 ======================
    private void showSoftInputForce() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

    private void hideSoftInput() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(vb.etSearch.getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int dp2px(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
    }

    // ====================== 适配器 ======================
    private class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder> {
        private List<String> dataList;

        public HistoryAdapter(List<String> dataList) {
            this.dataList = dataList;
        }

        @NonNull
        @Override
        public HistoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemSearchHistoryBinding binding = ItemSearchHistoryBinding.inflate(
                    LayoutInflater.from(parent.getContext()), parent, false);
            return new HistoryViewHolder(binding);
        }

        @Override
        public void onBindViewHolder(@NonNull HistoryViewHolder holder, int position) {
            String keyword = dataList.get(position);
            holder.binding.tvHistoryKeyword.setText(keyword);

            holder.itemView.setOnClickListener(v -> {
                addToHistory(keyword);
                vb.etSearch.setText(keyword);
                searchKeyboards(keyword);
                showResultView();
                hideSoftInput();
            });

            holder.binding.ivHistoryDelete.setOnClickListener(v -> {
                dataList.remove(position);
                saveHistoryToSP();
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, dataList.size());
                updateHistoryView();
            });
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }

        class HistoryViewHolder extends RecyclerView.ViewHolder {
            ItemSearchHistoryBinding binding;

            public HistoryViewHolder(@NonNull ItemSearchHistoryBinding binding) {
                super(binding.getRoot());
                this.binding = binding;
            }
        }
    }

    private class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
        private List<String> tagList;

        public TagAdapter(List<String> tagList) {
            this.tagList = tagList;
        }

        @NonNull
        @Override
        public TagViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemSearchTagSingleBinding binding = ItemSearchTagSingleBinding.inflate(
                    LayoutInflater.from(parent.getContext()), parent, false);
            return new TagViewHolder(binding);
        }

        @Override
        public void onBindViewHolder(@NonNull TagViewHolder holder, int position) {
            String tag = tagList.get(position);
            holder.binding.tvTag.setText(tag);

            holder.itemView.setOnClickListener(v -> {
                vb.etSearch.setText(tag);
                addToHistory(tag);
                searchKeyboards(tag);
                showResultView();
                hideSoftInput();
            });
        }

        @Override
        public int getItemCount() {
            return tagList.size();
        }

        class TagViewHolder extends RecyclerView.ViewHolder {
            ItemSearchTagSingleBinding binding;

            public TagViewHolder(@NonNull ItemSearchTagSingleBinding binding) {
                super(binding.getRoot());
                this.binding = binding;
            }
        }
    }

    private class TrendingAdapter extends RecyclerView.Adapter<TrendingAdapter.TrendingViewHolder> {
        private List<KeyboardItemInfo> mList;
        private Context mContext;

        public TrendingAdapter(List<KeyboardItemInfo> mList, Context mContext) {
            this.mList = mList;
            this.mContext = mContext;
        }

        @NonNull
        @Override
        public TrendingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            AdapterHomeItemSubBinding inflate = AdapterHomeItemSubBinding.inflate(
                    LayoutInflater.from(parent.getContext()),
                    parent,
                    false
            );
            return new TrendingViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull TrendingViewHolder holder, int position) {
            if (position >= mList.size()) return;
            KeyboardItemInfo beanDetails = mList.get(position);

            String thumbGif = beanDetails.getThumbGif() == null ? "" : beanDetails.getThumbGif();
            String thumb = beanDetails.getThumbUrl() == null ? "" : beanDetails.getThumbUrl();

            if (!thumbGif.isEmpty()) {
                AppCommonUtils.INSTANCE.loadWepJif(mContext, thumbGif, holder.binding.imageView);
            } else if (!thumb.isEmpty()) {
                Glide.with(mContext).load(thumb)
                        .error(R.drawable.place_holder)
                        .placeholder(R.drawable.place_holder)
                        .into(holder.binding.imageView);
            } else {
                holder.binding.imageView.setImageResource(R.drawable.place_holder);
            }

            holder.binding.fragme.setOnClickListener(v -> {
                if (beanDetails == null) return;
                Intent intentApply = new Intent(mContext, KeyboardSettingActivity.class);
                intentApply.putExtra(KeyboardSettingActivity.SOURCE_KEY, beanDetails);
                intentApply.putExtra(KeyboardSettingActivity.DISPLAY_URL_KEY, beanDetails.getImgPath());
                intentApply.putExtra(KeyboardSettingActivity.ZIP_URL_KEY, beanDetails.getZipPath());
                intentApply.putExtra(KeyboardSettingActivity.NAME_KEY, beanDetails.getTitleName());
                intentApply.putExtra(KeyboardSettingActivity.GIF_KEY, beanDetails.getImgGif());
                String intent_thumb = !thumbGif.isEmpty() ? thumbGif : thumb;
                intentApply.putExtra(KeyboardSettingActivity.THUMB_KEY, intent_thumb);
                mContext.startActivity(intentApply);
            });
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class TrendingViewHolder extends RecyclerView.ViewHolder {
            AdapterHomeItemSubBinding binding;

            public TrendingViewHolder(@NonNull AdapterHomeItemSubBinding binding) {
                super(binding.getRoot());
                this.binding = binding;
            }
        }
    }

    private class ResultAdapter extends RecyclerView.Adapter<ResultAdapter.ResultViewHolder> {
        private List<KeyboardItemInfo> mList;
        private Context mContext;

        public ResultAdapter(List<KeyboardItemInfo> mList, Context mContext) {
            this.mList = mList;
            this.mContext = mContext;
        }

        @NonNull
        @Override
        public ResultViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            AdapterHomeItemSubBinding inflate = AdapterHomeItemSubBinding.inflate(
                    LayoutInflater.from(parent.getContext()),
                    parent,
                    false
            );
            return new ResultViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ResultViewHolder holder, int position) {
            if (position >= mList.size()) return;
            KeyboardItemInfo beanDetails = mList.get(position);

            String thumbGif = beanDetails.getThumbGif() == null ? "" : beanDetails.getThumbGif();
            String thumb = beanDetails.getThumbUrl() == null ? "" : beanDetails.getThumbUrl();

            if (!thumbGif.isEmpty()) {
                AppCommonUtils.INSTANCE.loadWepJif(mContext, thumbGif, holder.binding.imageView);
            } else if (!thumb.isEmpty()) {
                Glide.with(mContext).load(thumb)
                        .error(R.drawable.place_holder)
                        .placeholder(R.drawable.place_holder)
                        .into(holder.binding.imageView);
            } else {
                holder.binding.imageView.setImageResource(R.drawable.place_holder);
            }

            holder.binding.fragme.setOnClickListener(v -> {
                if (beanDetails == null) return;
                Intent intentApply = new Intent(mContext, KeyboardSettingActivity.class);
                intentApply.putExtra(KeyboardSettingActivity.SOURCE_KEY, beanDetails);
                intentApply.putExtra(KeyboardSettingActivity.DISPLAY_URL_KEY, beanDetails.getImgPath());
                intentApply.putExtra(KeyboardSettingActivity.ZIP_URL_KEY, beanDetails.getZipPath());
                intentApply.putExtra(KeyboardSettingActivity.NAME_KEY, beanDetails.getTitleName());
                intentApply.putExtra(KeyboardSettingActivity.GIF_KEY, beanDetails.getImgGif());
                String intent_thumb = !thumbGif.isEmpty() ? thumbGif : thumb;
                intentApply.putExtra(KeyboardSettingActivity.THUMB_KEY, intent_thumb);
                mContext.startActivity(intentApply);
            });
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class ResultViewHolder extends RecyclerView.ViewHolder {
            AdapterHomeItemSubBinding binding;

            public ResultViewHolder(@NonNull AdapterHomeItemSubBinding binding) {
                super(binding.getRoot());
                this.binding = binding;
            }
        }
    }
}