package com.app.input.personalised.board.listhelpers;

import android.annotation.SuppressLint;
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.personalised.board.R;
import com.app.input.personalised.board.databean.ThemeCategory;
import com.app.input.personalised.board.helpers.FontTextView;

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

public class CategoryTabAdapter extends RecyclerView.Adapter<CategoryTabAdapter.CategoryViewHolder> {

    private Context mContext;
    private List<ThemeCategory> mList = new ArrayList<>();
    private int selectedPosition = 0;
    private OnCategoryClickListener mListener;

    public interface OnCategoryClickListener {
        void onCategoryClick(int position, ThemeCategory beanWrapper);
    }

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

    public void setOnCategoryClickListener(OnCategoryClickListener listener) {
        mListener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull CategoryViewHolder holder, @SuppressLint("RecyclerView") int position) {
        ThemeCategory beanWrapper = mList.get(position);
        holder.tvCategory.setText(beanWrapper.getParentName());
        
        boolean isSelected = position == selectedPosition;
        holder.tvCategory.setSelected(isSelected);
        holder.itemView.setSelected(isSelected);
        
        holder.itemView.setOnClickListener(v -> {
            int oldPosition = selectedPosition;
            selectedPosition = position;
            notifyItemChanged(oldPosition);
            notifyItemChanged(selectedPosition);
            
            if (mListener != null) {
                mListener.onCategoryClick(position, beanWrapper);
            }
        });
    }

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

    public void setSelectedPosition(int position) {
        int oldPosition = selectedPosition;
        selectedPosition = position;
        notifyItemChanged(oldPosition);
        notifyItemChanged(selectedPosition);
    }

    public static class CategoryViewHolder extends RecyclerView.ViewHolder {
        FontTextView tvCategory;

        public CategoryViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCategory = itemView.findViewById(R.id.tv_category);
        }
    }
}

