package com.app.input.breeze.board.listutils;

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

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

import com.app.input.breeze.board.bean.CategoryWrapper;
import com.app.input.breeze.board.databinding.CategoryCardItemBinding;
import com.bumptech.glide.Glide;

import java.util.List;

public class CategoryCardAdapter extends RecyclerView.Adapter<CategoryCardAdapter.CategoryCardViewHolder> {

    private Context mContext;
    private List<CategoryWrapper> mList;
    private OnCategoryCardClick mOnClick;

    public interface OnCategoryCardClick {
        void onCategoryClick(String categoryName);
    }

    public CategoryCardAdapter(Context context, List<CategoryWrapper> list, OnCategoryCardClick onClick) {
        mContext = context;
        mList = list;
        mOnClick = onClick;
    }

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

    @Override
    public void onBindViewHolder(@NonNull CategoryCardViewHolder holder, int position) {
        CategoryWrapper wrapper = mList.get(position);
        holder.bind(wrapper);
    }

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

    class CategoryCardViewHolder extends RecyclerView.ViewHolder {
        private CategoryCardItemBinding binding;

        public CategoryCardViewHolder(@NonNull CategoryCardItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(CategoryWrapper wrapper) {
            String categoryName = wrapper.getParentName();
            binding.categoryTitle.setText(categoryName);

            // 如果有主题，显示第一个主题的缩略图作为背景
            if (wrapper.getKeyboardList() != null && !wrapper.getKeyboardList().isEmpty()) {
                String thumbUrl = wrapper.getKeyboardList().get(0).getThumbUrl();
                if (thumbUrl != null && !thumbUrl.isEmpty()) {
                    Glide.with(mContext)
                        .load(thumbUrl)
                        .centerCrop()
                        .into(binding.categoryImage);
                }
            }

            binding.getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnClick != null) {
                        mOnClick.onCategoryClick(categoryName);
                    }
                }
            });
        }

    }
}

