package com.paint.sweet.drawing.sweetadapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import com.paint.sweet.drawing.R;
import com.paint.sweet.drawing.onClickListener;
import com.paint.sweet.drawing.sweetmanager.AppConstants;

import java.util.List;

public class HomeMainAdapter extends RecyclerView.Adapter<HomeMainAdapter.HomeVH> {
    private static final String TAG = "HomeAdapter";
    private List<String> nameList = AppConstants.getAllDir(); // 分类列表（Animals/Birds等）
    private onClickListener listener; // 点击事件回调
    private Context mCon;

    // 优化：网格列数、间距常量（统一管理）
    private static final int GRID_COLUMN_COUNT = 2; // 2列网格
    private static final int GRID_SPACING_DP = 8; // 网格间距8dp

    public void setListener(onClickListener listener) {
        this.listener = listener;
    }

    public HomeMainAdapter(Context mCon) {
        this.mCon = mCon;
    }

    @NonNull
    @Override
    public HomeVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载Item布局（确保adapter_home.xml与控件ID匹配）
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_main, parent, false);
        return new HomeVH(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HomeVH holder, int position) {
        String dir = nameList.get(position);
        Log.d(TAG, "绑定分类：" + dir);

        // 提取分类名称
        String categoryName = dir.substring(dir.lastIndexOf("_") + 1);
        holder.tvName.setText(categoryName);

        // ========== 核心修改：替换为2列网格布局（适配页面） ==========
        // 1. 创建GridLayoutManager（2列）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mCon, GRID_COLUMN_COUNT);
        // 2. 设置Item间距装饰器（避免图片挤在一起）
        holder.preRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int spacing = dp2px(GRID_SPACING_DP);
                outRect.left = spacing;
                outRect.right = spacing;
                outRect.top = spacing;
                outRect.bottom = spacing;
            }
        });
        holder.preRecycler.setLayoutManager(gridLayoutManager);

        // 3. 初始化子适配器（适配网格布局）
        HomeItemAdapter homeChildAdapter = new HomeItemAdapter(mCon, dir);
        homeChildAdapter.setListener(listener);
        holder.preRecycler.setAdapter(homeChildAdapter);

        // "查看全部"点击事件
        holder.seeAll.setOnClickListener(v -> {
            if (listener != null) {
                listener.onClickItem(true, dir);
            }
        });
    }

    @Override
    public int getItemCount() {
        // 空值保护：避免列表为空导致崩溃
        return nameList == null ? 0 : nameList.size();
    }

    // dp转px工具方法（适配不同设备）
    private int dp2px(int dp) {
        return (int) (dp * mCon.getResources().getDisplayMetrics().density + 0.5f);
    }

    // ViewHolder（优化：增加控件空指针检查）
    public static class HomeVH extends RecyclerView.ViewHolder {
        private TextView tvName; // 分类名称
        private RecyclerView preRecycler; // 图片列表
        private TextView seeAll; // 查看全部

        public HomeVH(@NonNull View itemView) {
            super(itemView);
            // 控件绑定（增加日志，方便排查ID错误）
            tvName = itemView.findViewById(R.id.tv_name);
            preRecycler = itemView.findViewById(R.id.pre_recycler);


            if (tvName == null || preRecycler == null || seeAll == null) {
                Log.e(TAG, "adapter_home.xml中存在未找到的控件ID，请检查布局文件");
            }
        }
    }

    // ========== 可选：刷新数据方法（适配分类列表更新） ==========
    public void refreshData(List<String> newNameList) {
        if (newNameList != null) {
            this.nameList = newNameList;
            notifyDataSetChanged(); // 局部刷新可改用notifyItemRangeChanged
        }
    }
}