package com.rainbow.app.keyboard.myadapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

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

import com.bumptech.glide.Glide;
import com.rainbow.app.keyboard.R;
import com.rainbow.app.keyboard.javabean.DetailsjavaBean;
import com.rainbow.app.keyboard.mycallback.DeleteCallback;
import com.rainbow.app.keyboard.mycallback.KBClickCallback;
import com.rainbow.app.keyboard.databinding.AdapterKbitemBinding;
import com.rainbow.app.keyboard.uiactivity.DetailkbActivity;
import com.rainbow.app.keyboard.utils.UtilsCommon;

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

public class KBItemAdapter extends RecyclerView.Adapter<KBItemAdapter.KeyboardViewHolder> {

    private Context mContext;
    private List<DetailsjavaBean> mList = new ArrayList<>();
    private DeleteCallback mMyremoveCallback;
    private KBClickCallback mKBClickCallback; // 新增：用于KBPreviewActivity的回调

    // 模式设置
    private boolean showFavoriteIcon = false; // 是否显示收藏图标
    private int spanCount = 2; // 每行显示数量
    private int itemSpacingDp = 10; // item之间的水平间距(dp)
    private int verticalSpacingDp = 12; // item之间的垂直间距(dp)
    private int sidePaddingDp = 10; // 左右边距(dp)
    private float aspectRatio = 0.65f; // 宽高比 10:7
    private boolean includeEdgePadding = true; // 是否包含边缘边距
    private int containerWidth = 0;
    private boolean isPreviewMode = false;

    public KBItemAdapter(Context context) {
        mContext = context;
    }

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

    /**
     * 设置KBPreviewActivity的回调
     */
    public void setItemClickListener(KBClickCallback callback) {
        this.mKBClickCallback = callback;
    }

    /**
     * 设置容器宽度（用于MainActivity中右侧网格）
     */
    public void setContainerWidth(int width) {
        this.containerWidth = width;
        notifyDataSetChanged();
    }

    /**
     * 预设配置：MainActivity首页使用（侧边栏布局）
     * 因为右侧只有屏幕的3/4宽度，间距需要调整
     */
    public void applyMainActivityConfig() {
        this.spanCount = 2;
        this.itemSpacingDp = 4;  // 适当增加间距
        this.verticalSpacingDp = 8;
        this.sidePaddingDp = 6;  // 减小边距
        this.aspectRatio = 0.65f;
        this.includeEdgePadding = false; // MainActivity中设为false，因为容器已经有padding
        this.containerWidth = 0; // 需要外部设置
        this.isPreviewMode = false;
        this.showFavoriteIcon = false;
        notifyDataSetChanged();
    }

    /**
     * 预设配置：CollectionActivity收藏页使用（全屏布局）
     */
    public void applyCollectionConfig() {
        this.spanCount = 2;
        this.itemSpacingDp = 6;
        this.verticalSpacingDp = 10;
        this.sidePaddingDp = 10;
        this.aspectRatio = 0.65f;
        this.includeEdgePadding = true;
        this.isPreviewMode = false;
        this.showFavoriteIcon = true; // 收藏页面显示收藏图标
        notifyDataSetChanged();
    }

    /**
     * 预设配置：KBPreviewActivity推荐列表使用（小图布局）
     */
    public void applyRecoItemConfig() {
        this.spanCount = 2;
        this.itemSpacingDp = 5; // 对应原RecoItemAdapter的 marginEnd="5dp"
        this.verticalSpacingDp = 8; // 对应原RecoItemAdapter的 marginBottom="8dp"
        this.sidePaddingDp = 0; // 不需要额外的左右边距
        this.aspectRatio = 0.0f; // 在预览模式下不使用宽高比，使用固定高度
        this.includeEdgePadding = false;
        this.isPreviewMode = true; // 关键：启用预览模式
        this.showFavoriteIcon = false; // 不显示收藏图标
        notifyDataSetChanged();
    }

    /**
     * 自定义配置（灵活调整）
     */
    public void applyCustomConfig(int spanCount, int itemSpacingDp, int verticalSpacingDp,
                                  int sidePaddingDp, float aspectRatio, boolean includeEdgePadding) {
        this.spanCount = spanCount;
        this.itemSpacingDp = itemSpacingDp;
        this.verticalSpacingDp = verticalSpacingDp;
        this.sidePaddingDp = sidePaddingDp;
        this.aspectRatio = aspectRatio;
        this.includeEdgePadding = includeEdgePadding;
        notifyDataSetChanged();
    }

    /**
     * 设置数据
     */
    public void setData(List<DetailsjavaBean> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    /**
     * 设置是否显示收藏图标
     */
    public void setShowFavoriteIcon(boolean show) {
        this.showFavoriteIcon = show;
    }

    /**
     * 设置每行显示数量
     */
    public void setSpanCount(int spanCount) {
        this.spanCount = spanCount;
        notifyDataSetChanged();
    }

    /**
     * 设置item水平间距(dp)
     */
    public void setItemSpacing(int spacingDp) {
        this.itemSpacingDp = spacingDp;
    }

    /**
     * 设置item垂直间距(dp)
     */
    public void setVerticalSpacing(int spacingDp) {
        this.verticalSpacingDp = spacingDp;
    }

    /**
     * 设置左右边距(dp)
     */
    public void setSidePadding(int paddingDp) {
        this.sidePaddingDp = paddingDp;
    }

    /**
     * 设置宽高比
     */
    public void setAspectRatio(float ratio) {
        this.aspectRatio = ratio;
    }

    /**
     * 设置是否包含边缘边距
     */
    public void setIncludeEdgePadding(boolean include) {
        this.includeEdgePadding = include;
    }

    /**
     * 设置移除回调
     */
    public void setRemoveCallback(DeleteCallback callback) {
        this.mMyremoveCallback = callback;
    }

    @NonNull
    @Override
    public KeyboardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        AdapterKbitemBinding binding = AdapterKbitemBinding.inflate(
                LayoutInflater.from(parent.getContext()), parent, false);

        // 动态计算item尺寸
        calculateAndSetItemSize(binding, parent);

        return new KeyboardViewHolder(binding);
    }

    /**
     * 动态计算并设置item尺寸
     */
    private void calculateAndSetItemSize(AdapterKbitemBinding binding, ViewGroup parent) {
        if (isPreviewMode) {
            // KBPreviewActivity模式：固定高度120dp
            int columnHeight = dpToPx(120); // 固定120dp高度

            // 设置FrameLayout尺寸
            ViewGroup.LayoutParams layoutParams = binding.getRoot().getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; // 宽度由GridLayoutManager自动分配
            layoutParams.height = columnHeight;

            // 设置边距
            if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) layoutParams;
                marginParams.bottomMargin = dpToPx(verticalSpacingDp); // 底部间距8dp
                // 水平间距将在onBindViewHolder中根据位置设置
            }

            binding.getRoot().setLayoutParams(layoutParams);

            // 设置CardView尺寸
            ViewGroup.LayoutParams cardParams = binding.cardView.getLayoutParams();
            cardParams.width = ViewGroup.LayoutParams.MATCH_PARENT; // 宽度充满
            cardParams.height = columnHeight;
            binding.cardView.setLayoutParams(cardParams);

        } else {
            // 普通网格布局：原有的动态计算逻辑
            int widthToUse;

            // 如果 containerWidth 还没有设置，尝试从RecyclerView获取
            if (containerWidth <= 0) {
                try {
                    // 尝试获取RecyclerView的实际宽度
                    RecyclerView recyclerView = findParentRecyclerView(binding.getRoot());
                    if (recyclerView != null && recyclerView.getWidth() > 0) {
                        widthToUse = recyclerView.getWidth();
                        // 缓存这个宽度供下次使用
                        containerWidth = widthToUse;
                    } else {
                        // 如果RecyclerView还没有测量，使用屏幕宽度
                        widthToUse = parent.getContext().getResources().getDisplayMetrics().widthPixels;
                    }
                } catch (Exception e) {
                    widthToUse = parent.getContext().getResources().getDisplayMetrics().widthPixels;
                }
            } else {
                // 使用指定的容器宽度
                widthToUse = containerWidth;
            }

            // 将dp转换为px
            int sidePaddingPx = dpToPx(sidePaddingDp);
            int itemSpacingPx = dpToPx(itemSpacingDp);

            // 计算可用宽度
            int totalPadding = includeEdgePadding ? sidePaddingPx * 2 : 0; // 左右边距
            int totalSpacing = itemSpacingPx * (spanCount - 1); // item之间的间距

            int availableWidth = widthToUse - totalPadding - totalSpacing;
            int columnWidth = availableWidth / spanCount;

            // 确保最小宽度
            int minWidth = dpToPx(120); // 最小120dp
            if (columnWidth < minWidth) {
                columnWidth = minWidth;
            }

            int columnHeight = (int) (columnWidth * aspectRatio);

            // 设置FrameLayout尺寸
            ViewGroup.LayoutParams layoutParams = binding.getRoot().getLayoutParams();
            layoutParams.width = columnWidth;
            layoutParams.height = columnHeight;

            // 设置边距
            if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) layoutParams;
                // 设置垂直间距（底部间距）
                marginParams.bottomMargin = dpToPx(verticalSpacingDp);
                // 水平间距将在onBindViewHolder中根据位置设置
            }

            binding.getRoot().setLayoutParams(layoutParams);

            // 设置CardView尺寸
            ViewGroup.LayoutParams cardParams = binding.cardView.getLayoutParams();
            cardParams.width = columnWidth;
            cardParams.height = columnHeight;
            binding.cardView.setLayoutParams(cardParams);
        }
    }

    /**
     * 查找父RecyclerView
     */
    private RecyclerView findParentRecyclerView(View view) {
        ViewParent parent = view.getParent();
        while (parent != null) {
            if (parent instanceof RecyclerView) {
                return (RecyclerView) parent;
            }
            parent = parent.getParent();
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull KeyboardViewHolder holder, @SuppressLint("RecyclerView") int position) {
        DetailsjavaBean detailsjavaBean = mList.get(position);

        // 显示或隐藏收藏图标
        holder.binding.favoriteIcon.setVisibility(showFavoriteIcon ? View.VISIBLE : View.GONE);

        // 设置收藏图标状态
        if (showFavoriteIcon) {
            holder.binding.favoriteIcon.setSelected(true); // 假设都是已收藏状态

            holder.binding.favoriteIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.binding.favoriteIcon.setSelected(false);
                    int adapterPosition = holder.getAdapterPosition();
                    if (adapterPosition != RecyclerView.NO_POSITION && mMyremoveCallback != null) {
                        mMyremoveCallback.OnRemoveLike(detailsjavaBean);
                    }
                }
            });
        }

        // 加载图片
        String thumbGif = detailsjavaBean.getThumbGif();
        String thumb = detailsjavaBean.getThumbUrl();

        if (thumbGif != null && !thumbGif.isEmpty()) {
            UtilsCommon.INSTANCE.loadWepJif(mContext, thumbGif, holder.binding.keyboardImage);
        } else {
            Glide.with(mContext)
                    .load(thumb)
                    .error(R.drawable.phold)
                    .placeholder(R.drawable.phold)
                    .centerCrop()
                    .into(holder.binding.keyboardImage);
        }

        // 设置卡片点击事件
        holder.binding.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openKeyboardPreview(detailsjavaBean, thumbGif, thumb);
            }
        });

        // 根据位置动态设置水平边距
        setHorizontalMargins(holder, position);
    }

    /**
     * 根据位置设置水平边距
     */
    private void setHorizontalMargins(KeyboardViewHolder holder, int position) {
        ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) layoutParams;

            int column = position % spanCount; // 获取当前列

            // 重置水平边距
            marginParams.leftMargin = 0;
            marginParams.rightMargin = 0;

            if (includeEdgePadding) {
                // 包含边缘边距的情况
                int sidePaddingPx = dpToPx(sidePaddingDp);
                int itemSpacingPx = dpToPx(itemSpacingDp);

                if (column == 0) {
                    // 第一列：左边距 + 右边距为item间距的一半
                    marginParams.leftMargin = sidePaddingPx;
                    marginParams.rightMargin = itemSpacingPx / 2;
                } else if (column == spanCount - 1) {
                    // 最后一列：左边距为item间距的一半 + 右边距
                    marginParams.leftMargin = itemSpacingPx / 2;
                    marginParams.rightMargin = sidePaddingPx;
                } else {
                    // 中间列：左右边距各为item间距的一半
                    marginParams.leftMargin = itemSpacingPx / 2;
                    marginParams.rightMargin = itemSpacingPx / 2;
                }
            } else {
                // 不包含边缘边距的情况
                int itemSpacingPx = dpToPx(itemSpacingDp);

                if (isPreviewMode) {
                    // 第一列：右边距5dp，第二列：无左边距
                    if (column == 0) {
                        // 第一列：右边距5dp
                        marginParams.rightMargin = itemSpacingPx;
                    }
                    // 第二列：不设置左边距，保持0
                } else {
                    // 普通网格布局：原有的间距逻辑
                    if (column == 0) {
                        // 第一列：右边距为item间距
                        marginParams.rightMargin = itemSpacingPx;
                    } else if (column == spanCount - 1) {
                        // 最后一列：左边距为item间距
                        marginParams.leftMargin = itemSpacingPx;
                    } else {
                        // 中间列：左右边距各为item间距
                        marginParams.leftMargin = itemSpacingPx;
                        marginParams.rightMargin = itemSpacingPx;
                    }
                }
            }

            holder.itemView.setLayoutParams(marginParams);
        }
    }

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

    /**
     * 打开键盘预览
     */
    private void openKeyboardPreview(DetailsjavaBean detailsjavaBean, String thumbGif, String thumb) {
        Intent intentApply = new Intent(mContext, DetailkbActivity.class);
        intentApply.putExtra(DetailkbActivity.SOURCE_KEY, detailsjavaBean);
        intentApply.putExtra(DetailkbActivity.DISPLAY_URL_KEY, detailsjavaBean.getImgPath());
        intentApply.putExtra(DetailkbActivity.ZIP_URL_KEY, detailsjavaBean.getZipPath());
        intentApply.putExtra(DetailkbActivity.NAME_KEY, detailsjavaBean.getTitleName());
        intentApply.putExtra(DetailkbActivity.GIF_KEY, detailsjavaBean.getImgGif());

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

        // 调用回调（用于KBPreviewActivity）
        if (mKBClickCallback != null) {
            mKBClickCallback.OnItemClickListener();
        }
    }

    /**
     * 移除指定位置的项目
     */
    public void removeItem(int position) {
        if (position >= 0 && position < mList.size()) {
            mList.remove(position);
            notifyItemRemoved(position);
            // 更新剩余item的位置
            if (position < mList.size()) {
                notifyItemRangeChanged(position, mList.size() - position);
            }
        }
    }

    /**
     * 添加项目
     */
    public void addItem(DetailsjavaBean item) {
        mList.add(item);
        notifyItemInserted(mList.size() - 1);
    }

    /**
     * 清空所有项目
     */
    public void clearAll() {
        mList.clear();
        notifyDataSetChanged();
    }

    public static class KeyboardViewHolder extends RecyclerView.ViewHolder {
        private AdapterKbitemBinding binding;

        public KeyboardViewHolder(@NonNull AdapterKbitemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    /**
     * 获取指定位置的项目
     */
    public DetailsjavaBean getItem(int position) {
        if (position >= 0 && position < mList.size()) {
            return mList.get(position);
        }
        return null;
    }

    /**
     * 查找指定项目的索引位置
     */
    public int getPositionOfItem(DetailsjavaBean item) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).equals(item)) {
                return i;
            }
        }
        return -1;
    }

    /**
     * dp转px
     */
    private int dpToPx(int dp) {
        if (mContext == null || mContext.getResources() == null) {
            return dp;
        }
        float density = mContext.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }
}