package com.app.wave.keyboard.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

import com.app.wave.keyboard.bean.WrapperBean;
import com.app.wave.keyboard.bean.DetailsBean;
import com.app.wave.keyboard.callback.MoreCallback;
import com.app.wave.keyboard.databinding.AdapterCategoryBinding;

import java.util.ArrayList;
import java.util.List;

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MainViewHolder> {
    private Context mContext;
    private List<WrapperBean> mList = new ArrayList<>();

    private MoreCallback mCallBack;

    public CategoryAdapter(Context context, List<WrapperBean> list) {
        mContext = context;
        this.mList = list;
    }

    public void setClickAction(MoreCallback callback) {
        mCallBack = callback;
    }

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

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        WrapperBean wrapperBean = mList.get(position);
        String parentName = wrapperBean.getParentName();
        holder.binding.className.setText(parentName);

        List<DetailsBean> keyboardList = wrapperBean.getKeyboardList();
        List<DetailsBean> displayList;
        if (keyboardList.size() > 7) {
            displayList = keyboardList.subList(0, 7);
        } else {
            displayList = keyboardList;
        }

        // 创建水平滑动的适配器
        CategoryItemAdapter categoryItemAdapter = new CategoryItemAdapter(mContext, displayList);
        categoryItemAdapter.setFixedWidthMode(150, 106);

        // 设置水平布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        holder.binding.childRecycler.setLayoutManager(layoutManager);
        holder.binding.childRecycler.setAdapter(categoryItemAdapter);

        // 移除旧的装饰器
        if (holder.binding.childRecycler.getItemDecorationCount() > 0) {
            holder.binding.childRecycler.removeItemDecorationAt(0);
        }

        HorizontalItemDecoration decoration = new HorizontalItemDecoration(16, 8, 16);
        holder.binding.childRecycler.addItemDecoration(decoration);

        // 设置查看更多按钮点击事件
        holder.binding.tvAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCallBack != null) {
                    mCallBack.OnClickSeeAll(parentName);
                }
            }
        });

        // 监听滚动，显示/隐藏右箭头提示
        holder.binding.childRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                boolean canScrollRight = recyclerView.canScrollHorizontally(1);
                // 检查 ImageView 是否存在
                if (holder.binding.ivScrollHint != null) {
                    holder.binding.ivScrollHint.setVisibility(canScrollRight ? View.VISIBLE : View.GONE);
                }
            }
        });

        // 初始检查是否可以滚动
        if (holder.binding.ivScrollHint != null) {
            holder.binding.childRecycler.post(new Runnable() {
                @Override
                public void run() {
                    boolean canScrollRight = holder.binding.childRecycler.canScrollHorizontally(1);
                    holder.binding.ivScrollHint.setVisibility(canScrollRight ? View.VISIBLE : View.GONE);
                }
            });
        }

        // ==================== 新增：箭头点击事件 ====================
        if (holder.binding.ivScrollHint != null) {
            holder.binding.ivScrollHint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    smoothScrollRight(holder.binding.childRecycler);
                }
            });
        }
    }

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

    public static class MainViewHolder extends RecyclerView.ViewHolder {
        private AdapterCategoryBinding binding;
        public MainViewHolder(@NonNull AdapterCategoryBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }

    /**
     * 水平间距装饰器 - 现在已实现完整的间距功能
     */
    public static class HorizontalItemDecoration extends RecyclerView.ItemDecoration {
        private final int itemSpacing; // item之间的间距
        private final int firstItemSpacing; // 第一个item的左边距
        private final int lastItemSpacing; // 最后一个item的右边距

        public HorizontalItemDecoration(int itemSpacing, int firstItemSpacing, int lastItemSpacing) {
            this.itemSpacing = itemSpacing;
            this.firstItemSpacing = firstItemSpacing;
            this.lastItemSpacing = lastItemSpacing;
        }

        public HorizontalItemDecoration(int itemSpacing) {
            this(itemSpacing, itemSpacing, itemSpacing);
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                                   @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);

            int position = parent.getChildAdapterPosition(view);
            if (position == RecyclerView.NO_POSITION) {
                return;
            }

            int itemCount = state.getItemCount();

            // 所有 item 都设置上下的间距为0
            outRect.top = 0;
            outRect.bottom = 0;

            // 第一个 item：左边距为 firstItemSpacing，右边距为 itemSpacing/2
            if (position == 0) {
                outRect.left = firstItemSpacing;
                outRect.right = itemSpacing / 2;
            }
            // 最后一个 item：左边距为 itemSpacing/2，右边距为 lastItemSpacing
            else if (position == itemCount - 1) {
                outRect.left = itemSpacing / 2;
                outRect.right = lastItemSpacing;
            }
            // 中间的 item：左右边距各为 itemSpacing/2
            else {
                outRect.left = itemSpacing / 2;
                outRect.right = itemSpacing / 2;
            }
        }
    }

    /**
     * 平滑滚动到右侧
     */
    private void smoothScrollRight(RecyclerView recyclerView) {
        if (recyclerView == null || recyclerView.getLayoutManager() == null) {
            return;
        }

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

        // 获取当前第一个可见的item位置
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        if (firstVisibleItemPosition == RecyclerView.NO_POSITION) {
            return;
        }

        // 获取当前第一个可见item的View
        View firstVisibleView = layoutManager.findViewByPosition(firstVisibleItemPosition);
        if (firstVisibleView == null) {
            return;
        }

        // 计算滚动的距离（向右移动一个item的宽度 + 间距）
        int itemWidth = firstVisibleView.getWidth();

        // 获取item装饰间距（如果有）
        int itemSpacing = 16; // 这是你在HorizontalItemDecoration中设置的

        // 滚动距离 = item宽度 + 间距（这样每次点击可以看到下一个item）
        int scrollDistance = itemWidth + itemSpacing;

        // 平滑滚动
        recyclerView.smoothScrollBy(scrollDistance, 0);

        // 或者使用这种方式滚动到下一个item
        // if (firstVisibleItemPosition + 1 < recyclerView.getAdapter().getItemCount()) {
        //     recyclerView.smoothScrollToPosition(firstVisibleItemPosition + 1);
        // }
    }

    /**
     * 另一种实现方式：直接滚动到下一个位置
     */
    private void scrollToNextItem(RecyclerView recyclerView) {
        if (recyclerView == null || recyclerView.getLayoutManager() == null) {
            return;
        }

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

        // 获取当前第一个完全可见的item位置
        int firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();

        // 获取当前最后一个完全可见的item位置
        int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();

        if (firstCompletelyVisibleItemPosition == RecyclerView.NO_POSITION) {
            return;
        }

        int nextPosition;

        // 如果最后一个完全可见的item不是最后一个item，则滚动让下一个item完全可见
        if (lastCompletelyVisibleItemPosition < recyclerView.getAdapter().getItemCount() - 1) {
            nextPosition = lastCompletelyVisibleItemPosition + 1;
        }
        // 否则，滚动到下一个item（可能只显示一部分）
        else if (firstCompletelyVisibleItemPosition < recyclerView.getAdapter().getItemCount() - 1) {
            nextPosition = firstCompletelyVisibleItemPosition + 1;
        }
        // 如果已经是最后一个，就不滚动
        else {
            return;
        }

        // 平滑滚动到指定位置，让目标item位于起始位置
        layoutManager.scrollToPositionWithOffset(nextPosition, 8); // 8是第一个item的左边距
    }
}