package com.wall.proshot.wallpapers.myfragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wall.proshot.wallpapers.FreeWallPaper;
import com.wall.proshot.wallpapers.myacctivity.ListActivity;
import com.wall.proshot.wallpapers.myacctivity.WallPaperActivity;
import com.wall.proshot.wallpapers.myconnector.OnItemClick;
import com.wall.proshot.wallpapers.myitem.MyItemMain;
import com.wall.proshot.wallpapers.bean.Data;
import com.wall.proshot.wallpapers.mytool.MyComUtils;
import com.wall.proshot.wallpapers.databinding.MyFragmentMainBinding;

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

public class FragmentMain extends Fragment implements OnItemClick {
    private MyFragmentMainBinding vb;

    public FragmentMain() {
    }

    public static FragmentMain newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(MyComUtils.key_index, type);
        FragmentMain fragment = new FragmentMain();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 修复布局绑定：传入 container 和 attachToRoot=false，避免布局层级异常
        vb = MyFragmentMainBinding.inflate(inflater, container, false);
        initTabVp();
        return vb.getRoot();
    }

    private void initTabVp() {
        List<String> data = new ArrayList<>();
        // 循环获取分类名称，直到获取到数据（避免空列表）
        while (data.isEmpty()) {
            data = FreeWallPaper.getCategoryNames();
            // 防止无限循环（若获取失败，最多循环3次）
            if (data.isEmpty() && FreeWallPaper.getCategoryNames() == null) {
                break;
            }
        }
        vb.loadingPb.setVisibility(View.GONE);
        // 初始化两列分类列表
        initList(data);
    }

    private void initList(List<String> data) {
        // 1. 初始化分类适配器
        MyItemMain adHomeParent = new MyItemMain();
        adHomeParent.setData(data);
        adHomeParent.setInfoWallpaperListener(this);

        // 2. 核心：两列网格布局管理器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 2);
        // 确保每个分类item占1列（避免某些item占满两列）
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return 1;
            }
        });

        // 3. 自定义两列间距（优化视觉效果，与其他页面保持一致）
        int spacing = MyComUtils.dp2Px(10); // 10dp间距（转px适配不同屏幕）
        vb.classRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                int column = position % 2; // 0=左列，1=右列

                // 左右间距：左列右边5dp，右列左边5dp，总间距10dp
                outRect.left = column == 0 ? 0 : spacing / 2;
                outRect.right = column == 0 ? spacing / 2 : 0;

                // 上下间距：第一行顶部10dp，其余行上下各5dp
                outRect.top = position < 2 ? spacing : spacing / 2;
                outRect.bottom = spacing / 2;
            }
        });

        // 4. 设置RecyclerView配置（优化性能+两列布局）
        vb.classRecycler.setLayoutManager(gridLayoutManager);
        vb.classRecycler.setAdapter(adHomeParent);
        vb.classRecycler.setHasFixedSize(true); // 固定item大小，提升滚动流畅度
        vb.classRecycler.setItemViewCacheSize(20); // 增加缓存数量
        vb.classRecycler.setNestedScrollingEnabled(false); // 禁用嵌套滚动，避免卡顿

        // 保留原有item装饰器（若ItemHelper是间距装饰器，可根据需求选择保留/替换）
        // 注意：避免重复添加间距，若ItemHelper已设置间距，可注释上面的自定义ItemDecoration
        // ItemHelper itemHelper = new ItemHelper(10, 10, 0);
        // vb.classRecycler.addItemDecoration(itemHelper);
    }

    @Override
    public void onItemClickAction(Data info) {
        if (info == null) return; // 空数据容错
        Intent intent = new Intent(requireContext(), WallPaperActivity.class);
        intent.putExtra(MyComUtils.key_info, info);
        startActivity(intent);
    }

    @Override
    public void onClickMore(String name) {
        if (name == null || name.isEmpty()) return; // 空名称容错
        Intent intent = new Intent(requireContext(), ListActivity.class);
        intent.putExtra(ListActivity.key_index, name);
        startActivity(intent);
    }

    public void scrollToTop() {
        if (vb.classRecycler != null) {
            vb.classRecycler.scrollToPosition(0);
        }
    }

}