package com.rainbow.app.keyboard.myadapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import com.rainbow.app.keyboard.R;
import com.rainbow.app.keyboard.javabean.DetailsjavaBean;
import com.rainbow.app.keyboard.javabean.WrapperjavaBean;

import java.util.List;

public class NavCategoryAdapter extends RecyclerView.Adapter<NavCategoryAdapter.NavViewHolder> {

    private Context context;
    private List<WrapperjavaBean> categoryList;
    private CategoryClickListener categoryClickListener;
    private int selectedPosition = 0; // 默认选中第一个分类

    public interface CategoryClickListener {
        void onCategoryClick(String categoryName, List<DetailsjavaBean> keyboards);
    }

    public NavCategoryAdapter(Context context, List<WrapperjavaBean> categoryList) {
        this.context = context;
        this.categoryList = categoryList;
    }

    public void setCategoryClickListener(CategoryClickListener listener) {
        this.categoryClickListener = listener;
    }

    @NonNull
    @Override
    public NavViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_nav_category, parent, false);
        return new NavViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull NavViewHolder holder, @SuppressLint("RecyclerView") int position) {
        WrapperjavaBean category = categoryList.get(position);
        String categoryName = category.getParentName();
        List<DetailsjavaBean> keyboards = category.getKeyboardList();

        holder.categoryName.setText(categoryName);

        // 设置选中状态
        if (position == selectedPosition) {
            holder.itemView.setBackgroundResource(R.color.nav_selected_bg);
            holder.categoryName.setTextColor(context.getResources().getColor(R.color.text_color_selected));
        } else {
            holder.itemView.setBackgroundResource(R.color.transparent);
            holder.categoryName.setTextColor(context.getResources().getColor(R.color.text_color));
        }

        holder.itemView.setOnClickListener(v -> {
            selectedPosition = position;
            notifyDataSetChanged(); // 更新选中状态
            if (categoryClickListener != null) {
                categoryClickListener.onCategoryClick(categoryName, keyboards);
            }
        });
    }

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

    static class NavViewHolder extends RecyclerView.ViewHolder {
        TextView categoryName;

        public NavViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryName = itemView.findViewById(R.id.nav_category_name);
        }
    }
}