package com.house.wallpapers.myfragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.graphics.Rect;
import android.util.Log;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.house.wallpapers.App;
import com.house.wallpapers.R;
import com.house.wallpapers.myactivity.MyListActivity;
import com.house.wallpapers.adapter.OnItemclick;
import com.house.wallpapers.myitem.ItemHome;
import com.house.wallpapers.mybean.Data;
import com.house.wallpapers.mytool.Comutils;
import com.house.wallpapers.databinding.FragmentHomeBinding;

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

public class FragmentHome extends Fragment implements OnItemclick {
    private FragmentHomeBinding vb; // 与布局文件 fragment_main.xml 绑定
    private ItemHome categoryAdapter; // RecyclerView 适配器
    private ProgressBar loadingPb; // 加载进度条（布局中 id=loading_pb）
    private RecyclerView classRecycler; // 分类列表 RecyclerView（布局中 id=class_recycler）
    private static final String TAG = "FragmentMain_Debug";
    public static FragmentHome newInstance(int type) {
        FragmentHome fragment = new FragmentHome();
        Bundle bundle = new Bundle();
        bundle.putInt(Comutils.key_index, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView：创建视图");
        vb = FragmentHomeBinding.inflate(inflater, container, false);
        loadingPb = vb.getRoot().findViewById(R.id.loading_pb);
        classRecycler = vb.getRoot().findViewById(R.id.class_recycler);
        return vb.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated：初始化分类数据");
        initCategoryData();
    }
    private void initCategoryData() {
        // 显示加载进度条
        if (loadingPb != null) {
            loadingPb.setVisibility(View.VISIBLE);
        }

        // 从 MyApp 获取全局分类列表
        List<String> categoryNames = App.getCategoryNames();
        Log.d(TAG, "从 MyApp 获取分类：" + categoryNames);
        if (categoryNames == null || categoryNames.isEmpty()) {
            categoryNames = new ArrayList<>();
            categoryNames.add("Featured");
            categoryNames.add("Animals");
            categoryNames.add("Experimental");
            categoryNames.add("Film");
            categoryNames.add("Nature");
            categoryNames.add("Patterns");
            categoryNames.add("Street");
            categoryNames.add("Travel");
            Log.d(TAG, "使用兜底分类：" + categoryNames);
        }

        if (loadingPb != null) {
            loadingPb.setVisibility(View.GONE);
        }
        initRecyclerView(categoryNames);
    }

    private void initRecyclerView(List<String> categoryNames) {
        Context context = getContext();
        if (context == null || classRecycler == null) {
            Log.e(TAG, "context 为空或 RecyclerView 未绑定");
            return;
        }

        classRecycler.setLayoutManager(new GridLayoutManager(context, 2));
        int recyclerPadding = dpToPx(context, 8);
        classRecycler.setPadding(recyclerPadding, recyclerPadding, recyclerPadding, recyclerPadding);
        classRecycler.setClipToPadding(false);

        int spacing = dpToPx(context, 5);
        classRecycler.addItemDecoration(new GridSpacingItemDecoration(2, spacing, true));
        classRecycler.setOverScrollMode(View.OVER_SCROLL_NEVER);
        categoryAdapter = new ItemHome();
        categoryAdapter.setData(categoryNames);
        categoryAdapter.setInfoWallpaperListener(this);
        classRecycler.setAdapter(categoryAdapter);

        Log.d(TAG, "RecyclerView 初始化完成：内边距=" + recyclerPadding + "px，Item间距=" + spacing + "px，Item数量=" + categoryNames.size());
    }

    private int dpToPx(Context context, float dpValue) {
        return (int) (dpValue * context.getResources().getDisplayMetrics().density + 0.5f);
    }
    @Override
    public void onItemClickAction(Data info) {
        Context context = getContext();
        if (context != null && info != null && info.getCategoryName() != null) {
            Log.d(TAG, "点击分类：" + info.getCategoryName());
            Intent intent = new Intent(context, MyListActivity.class);
            intent.putExtra(MyListActivity.key_index, info.getCategoryName());
            startActivity(intent);
        }
    }
    public static class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
        private int spanCount; // 列数
        private int spacing;
        private boolean includeEdge; // 是否包含边缘间距

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            if (position == RecyclerView.NO_POSITION) return;

            int column = position % spanCount;
            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount;
                outRect.right = (column + 1) * spacing / spanCount;
            } else {
                outRect.left = column * spacing / spanCount;
                outRect.right = spacing - (column + 1) * spacing / spanCount;
            }
            if (position < spanCount && includeEdge) {
                outRect.top = spacing;
            }
            outRect.bottom = spacing;
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (classRecycler != null) {
            classRecycler.setAdapter(null);
            classRecycler.setLayoutManager(null);
        }
        vb = null;
        loadingPb = null;
        classRecycler = null;
        categoryAdapter = null;
    }
}