package com.app.wave.keyboard.adapter;

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

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

import com.app.wave.keyboard.R;
import com.app.wave.keyboard.bean.DetailsBean;
import com.app.wave.keyboard.databinding.AdapterCategoryItemBinding;
import com.app.wave.keyboard.ui.KeyboardPreviewActivity;
import com.app.wave.keyboard.utils.Comutils;
import com.bumptech.glide.Glide;

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

public class CategoryItemAdapter extends RecyclerView.Adapter<CategoryItemAdapter.ChildViewHolder> {

    private Context mContext;
    private List<DetailsBean> mList = new ArrayList<>();
    private boolean isFixedWidth = true; // 默认为固定宽度模式
    private int fixedWidthDp = 150; // 保存dp值而不是px值
    private int fixedHeightDp = 106; // 保存dp值而不是px值
    private int spanCount = 3; // 用于自适应宽度模式

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

    // 设置固定宽度模式（用于HomepageFragment）
    public void setFixedWidthMode(int widthDp, int heightDp) {
        this.isFixedWidth = true;
        this.fixedWidthDp = widthDp;
        this.fixedHeightDp = heightDp;
    }

    // 设置自适应宽度模式（用于MoreActivity）
    public void setAdaptiveWidthMode(int spanCount) {
        this.isFixedWidth = false;
        this.spanCount = spanCount;
    }

    @NonNull
    @Override
    public ChildViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        AdapterCategoryItemBinding inflate = AdapterCategoryItemBinding.inflate(LayoutInflater.from(parent.getContext()));

        View itemView = inflate.getRoot();

        if (itemView.getLayoutParams() == null) {
            itemView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            ));
        }

        ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();

        if (isFixedWidth) {
            // 固定宽度模式
            layoutParams.width = dpToPx(fixedWidthDp);
            layoutParams.height = dpToPx(fixedHeightDp);
        } else {
            // 自适应宽度模式
            int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
            int horizontalPadding = dpToPx(20);
            int itemSpacing = dpToPx(8);

            int availableWidth = screenWidth - horizontalPadding - (spanCount - 1) * itemSpacing;
            int columnWidth = availableWidth / spanCount;

            layoutParams.width = columnWidth;
            layoutParams.height = (int) (columnWidth * 0.7); // 保持宽高比
        }

        itemView.setLayoutParams(layoutParams);

        return new ChildViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull ChildViewHolder holder, int position) {
        DetailsBean detailsBean = mList.get(position);

        String thumbGif = detailsBean.getThumbGif();
        String thumb = detailsBean.getThumbUrl();

        // 加载图片
        if (thumbGif != null && !thumbGif.isEmpty()) {
            Comutils.INSTANCE.loadWepJif(mContext, thumbGif, holder.binding.imageView);
        } else {
            Glide.with(mContext)
                    .load(thumb)
                    .error(R.drawable.placeholder)
                    .placeholder(R.drawable.placeholder)
                    .centerCrop()
                    .into(holder.binding.imageView);
        }

        // 点击事件
        holder.binding.fragme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentApply = new Intent(mContext, KeyboardPreviewActivity.class);
                intentApply.putExtra(KeyboardPreviewActivity.SOURCE_KEY, detailsBean);
                intentApply.putExtra(KeyboardPreviewActivity.DISPLAY_URL_KEY, detailsBean.getImgPath());
                intentApply.putExtra(KeyboardPreviewActivity.ZIP_URL_KEY, detailsBean.getZipPath());
                intentApply.putExtra(KeyboardPreviewActivity.NAME_KEY, detailsBean.getTitleName());
                intentApply.putExtra(KeyboardPreviewActivity.GIF_KEY, detailsBean.getImgGif());

                String intent_thumb;
                if (thumbGif != null && !thumbGif.isEmpty()) {
                    intent_thumb = thumbGif;
                } else {
                    intent_thumb = thumb;
                }
                intentApply.putExtra(KeyboardPreviewActivity.THUMB_KEY, intent_thumb);
                mContext.startActivity(intentApply);
            }
        });
    }

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

    public static class ChildViewHolder extends RecyclerView.ViewHolder {
        private AdapterCategoryItemBinding binding;

        public ChildViewHolder(@NonNull AdapterCategoryItemBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }

    private int dpToPx(int dp) {
        if (mContext == null || mContext.getResources() == null) {
            return dp; // 返回原始值作为fallback
        }
        float density = mContext.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }
}