package com.app.brush.guitar.ink.gallery;


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

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

import com.app.brush.guitar.ink.R;
import com.app.brush.guitar.ink.drama.EphemeralWrapper;
import com.app.brush.guitar.ink.canvas.CacophonyViewAll;
import com.app.brush.guitar.ink.databinding.NiceAdapterMainHomeBinding;
import com.app.brush.guitar.ink.databinding.ThinAdapterRecommendedHomeBinding;
import com.app.brush.guitar.ink.drama.DichotomyDetails;
import com.app.brush.guitar.ink.iguana.ListDecorationFossil;

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

public class HomeFluctuate extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_RECOMMENDED = 0;
    private static final int TYPE_CATEGORY = 1;

    private Context mContext;
    private List<EphemeralWrapper> mList = new ArrayList<>();
    private CacophonyViewAll mCallBack;

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

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

    @Override
    public int getItemViewType(int position) {
        // 第一个是推荐模块
        return position == 0 ? TYPE_RECOMMENDED : TYPE_CATEGORY;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_RECOMMENDED) {
            ThinAdapterRecommendedHomeBinding binding = ThinAdapterRecommendedHomeBinding.inflate(
                LayoutInflater.from(parent.getContext()), parent, false);
            return new RecommendedViewHolder(binding);
        } else {
            NiceAdapterMainHomeBinding binding = NiceAdapterMainHomeBinding.inflate(
                LayoutInflater.from(parent.getContext()), parent, false);
            return new CategoryViewHolder(binding);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof RecommendedViewHolder) {
            bindRecommendedViewHolder((RecommendedViewHolder) holder);
        } else if (holder instanceof CategoryViewHolder) {
            // 推荐模块占第一个位置，所以分类从 position-1 开始
            int categoryIndex = position - 1;
            if (categoryIndex >= 0 && categoryIndex < mList.size()) {
                bindCategoryViewHolder((CategoryViewHolder) holder, mList.get(categoryIndex));
            }
        }
    }

    private void bindRecommendedViewHolder(RecommendedViewHolder holder) {
        // 获取所有分类的键盘，合并作为推荐内容
        List<DichotomyDetails> recommendedList = new ArrayList<>();
        for (EphemeralWrapper wrapper : mList) {
            if (wrapper.getKeyboardList() != null && !wrapper.getKeyboardList().isEmpty()) {
                int count = Math.min(2, wrapper.getKeyboardList().size());
                for (int i = 0; i < count; i++) {
                    recommendedList.add(wrapper.getKeyboardList().get(i));
                }
            }
        }
        
        RecommendedCardNurture adapter = new RecommendedCardNurture(mContext, recommendedList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        holder.binding.recyclerRecommended.setLayoutManager(layoutManager);
        holder.binding.recyclerRecommended.setAdapter(adapter);
        
        // 添加横向间距装饰
        if (holder.binding.recyclerRecommended.getItemDecorationCount() <= 0) {
            // 为横向列表添加间距
            holder.binding.recyclerRecommended.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(@NonNull android.graphics.Rect outRect, @NonNull View view, 
                    @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    int position = parent.getChildAdapterPosition(view);
                    int itemCount = parent.getAdapter() != null ? parent.getAdapter().getItemCount() : 0;
                    if (position == 0) {
                        outRect.left = 0;
                    } else {
                        outRect.left = (int) ListDecorationFossil.dpToPx(14);
                    }
                    // 最后一个卡片添加右边距
                    if (position == itemCount - 1) {
                        outRect.right = (int) ListDecorationFossil.dpToPx(20);
                    } else {
                        outRect.right = 0;
                    }
                }
            });
        }
        
    }

    private void bindCategoryViewHolder(CategoryViewHolder holder, EphemeralWrapper beanWrapper) {
        String parentName = beanWrapper.getParentName();
        holder.binding.className.setText(parentName);

        setCategoryIconAndSubtitle(holder, parentName);
        List<DichotomyDetails> keyboardList = beanWrapper.getKeyboardList();
        if (keyboardList == null || keyboardList.isEmpty()) {
            holder.binding.childRecycler.setAdapter(null);
            return;
        }
        
        ListDecorationFossil listDecoration = new ListDecorationFossil(7, 14, 0);
        int itemCount = Math.min(4, keyboardList.size());
        List<DichotomyDetails> displayList = keyboardList.subList(0, itemCount);
        HomeChildGalvanize homeChildAdapter = new HomeChildGalvanize(mContext, displayList);
        
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        holder.binding.childRecycler.setLayoutManager(layoutManager);
        holder.binding.childRecycler.setAdapter(homeChildAdapter);
        
        if (holder.binding.childRecycler.getItemDecorationCount() <= 0) {
            holder.binding.childRecycler.addItemDecoration(listDecoration);
        }
        
        holder.binding.ivArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCallBack != null) {
                    mCallBack.OnClickSeeAll(parentName);
                }
            }
        });
    }

    private void setCategoryIconAndSubtitle(CategoryViewHolder holder, String categoryName) {
        int iconRes = R.mipmap.aesthetic;
        String subtitle = "Soft · Romantic · Popular";
        String lowerName = categoryName.toLowerCase();
        
        if (lowerName.contains("recommend")) {
            iconRes = R.mipmap.recommend;
        } else if (lowerName.contains("aesthetic") || lowerName.contains("美学")) {
            iconRes = R.mipmap.aesthetic;
        } else if (lowerName.contains("cool") || lowerName.contains("酷")) {
            iconRes = R.mipmap.zcool;
            subtitle = "Modern · Bold · Trendy";
        } else if (lowerName.contains("cute") || lowerName.contains("可爱")) {
            iconRes = R.mipmap.cute;
            subtitle = "Sweet · Lovely · Charming";
        } else if (lowerName.contains("festival")) {
            iconRes = R.mipmap.festival;
        } else if (lowerName.contains("live")) {
            iconRes = R.mipmap.live;
        } else if (lowerName.contains("love")) {
            iconRes = R.mipmap.glove;
        } else if (lowerName.contains("neon")) {
            iconRes = R.mipmap.neon;
        } else if (lowerName.contains("gravity")) {
            iconRes = R.mipmap.beautiful;
        } else if (lowerName.contains("super") && lowerName.contains("theme")) {
            iconRes = R.mipmap.su;
        }
        
        holder.binding.ivCategoryIcon.setImageResource(iconRes);
        holder.binding.tvCategorySubtitle.setText(subtitle);
    }

    @Override
    public int getItemCount() {
        // 推荐模块 + 分类数量
        return 1 + mList.size();
    }

    // 推荐模块ViewHolder
    public static class RecommendedViewHolder extends RecyclerView.ViewHolder {
        private ThinAdapterRecommendedHomeBinding binding;
        
        public RecommendedViewHolder(@NonNull ThinAdapterRecommendedHomeBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    // 分类ViewHolder
    public static class CategoryViewHolder extends RecyclerView.ViewHolder {
        private NiceAdapterMainHomeBinding binding;
        
        public CategoryViewHolder(@NonNull NiceAdapterMainHomeBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
