package com.ardrawing.ardrawingspace.util;

import android.graphics.Rect;
import android.view.View;

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

import com.ardrawing.ardrawingspace.MyApplication;

public class ItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalSpacing; // 垂直间距（dp）
    private final int horizontalSpacing; // 水平间距（dp）
    private final int edgeSpacing; // 边缘额外间距（dp）

    public ItemDecoration(int verticalSpacingDp, int horizontalSpacingDp, int edgeSpacingDp) {
        this.verticalSpacing = Math.round(dpToPx(verticalSpacingDp));
        this.horizontalSpacing = Math.round(dpToPx(horizontalSpacingDp));
        this.edgeSpacing = Math.round(dpToPx(edgeSpacingDp));
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager == null) {
            return; // 防止空指针异常
        }

        int position = parent.getChildAdapterPosition(view);
        if (position == RecyclerView.NO_POSITION) {
            return; // 无效位置，直接返回
        }

        // 默认处理 LinearLayoutManager
        outRect.left = verticalSpacing;
        outRect.right = verticalSpacing;
        outRect.bottom = horizontalSpacing;

        // 处理 Grid 和 StaggeredGrid 布局
        if (layoutManager instanceof GridLayoutManager) {
            handleGridLayout(outRect, view, parent, (GridLayoutManager) layoutManager, position);
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            handleStaggeredGridLayout(outRect, view, parent, (StaggeredGridLayoutManager) layoutManager);
        }
    }

    private void handleGridLayout(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent,
                                  @NonNull GridLayoutManager layoutManager, int position) {
        int spanCount = layoutManager.getSpanCount();
        GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) view.getLayoutParams();
        int spanSize = layoutManager.getSpanSizeLookup().getSpanSize(position);
        int spanIndex = lp.getSpanIndex();

        if (spanSize == spanCount) { // 全跨列项
            outRect.left = verticalSpacing + edgeSpacing;
            outRect.right = verticalSpacing + edgeSpacing;
        } else { // 普通网格项
            int totalSpacing = (verticalSpacing * (spanCount + 1) + 2 * edgeSpacing) / spanCount;
            int left = verticalSpacing * (spanIndex + 1) - totalSpacing * spanIndex + edgeSpacing;
            int right = totalSpacing - left;
            outRect.left = left;
            outRect.right = right;
        }
        outRect.bottom = horizontalSpacing;
    }

    private void handleStaggeredGridLayout(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent,
                                           @NonNull StaggeredGridLayoutManager layoutManager) {
        int spanCount = layoutManager.getSpanCount();
        StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
        int spanIndex = lp.getSpanIndex();

        if (lp.isFullSpan()) { // 全跨列项
            outRect.left = verticalSpacing + edgeSpacing;
            outRect.right = verticalSpacing + edgeSpacing;
        } else { // 普通瀑布流项
            int totalSpacing = (verticalSpacing * (spanCount + 1) + 2 * edgeSpacing) / spanCount;
            int left = verticalSpacing * (spanIndex + 1) - totalSpacing * spanIndex + edgeSpacing;
            int right = totalSpacing - left;
            outRect.left = left;
            outRect.right = right;
        }
        outRect.bottom = horizontalSpacing;
    }

    public static float dpToPx(float dpValue) {
        if (MyApplication.getContext() == null) {
            throw new IllegalStateException("Application context is null");
        }
        float density = MyApplication.getContext().getResources().getDisplayMetrics().density;
        return density * dpValue + 0.5f;
    }
}
