package com.idle.wall.idlefragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.idle.wall.R;
import com.idle.wall.idleactivity.IdleWallActivity;
import com.idle.wall.idleadapter.OnItemclick;
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idleitem.ItemIdleList;
import com.idle.wall.idletool.Comutils;
import com.idle.wall.idletool.Itemhelper;
import com.idle.wall.idletool.ObectManager;
import java.util.ArrayList;
import java.util.List;

public class FragmentCategoryPage extends Fragment implements OnItemclick {
    private RecyclerView recyclerView;
    private ItemIdleList categoryAdapter;
    private List<IdleData> categoryDataList;
    private ProgressBar loadingView;
    private String categoryName;
    private TextView emptyView;

    public static FragmentCategoryPage newInstance(String categoryName) {
        FragmentCategoryPage fragment = new FragmentCategoryPage();
        Bundle bundle = new Bundle();
        bundle.putString("key_index", categoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category_page, container, false);

        // 同步查找控件
        recyclerView = view.findViewById(R.id.category_recycler);
        loadingView = view.findViewById(R.id.loading_category);

        if (recyclerView == null) {
            View emptyView = new View(requireContext());
            emptyView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
            ));
            return emptyView;
        }

        parseCategoryName();
        initCategoryLayout();
        loadCategoryData(); // 同步加载数据

        return view;
    }

    private void parseCategoryName() {
        Bundle args = getArguments();
        if (args != null) {
            categoryName = args.getString("key_index");

        }
    }

    private void initCategoryLayout() {
        if (recyclerView == null) return;

        // 同步初始化RecyclerView
        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemViewCacheSize(10);

        if (recyclerView.getItemDecorationCount() == 0) {
            int spacing = Comutils.dp2px(requireContext(), 2);
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    outRect.left = spacing / 2;
                    outRect.right = spacing / 2;
                    outRect.top = spacing / 2;
                    outRect.bottom = spacing / 2;
                }
            });
            Itemhelper itemHelper = new Itemhelper(0, 0, 0);
            recyclerView.addItemDecoration(itemHelper);
        }

        // 同步创建Adapter
        categoryAdapter = new ItemIdleList(requireContext(), 0, false);
        categoryAdapter.setInfoWallpaperListener(this);
        recyclerView.setAdapter(categoryAdapter);

        if (loadingView != null) {
            loadingView.setVisibility(View.VISIBLE);
        }
        if (emptyView != null) {
            emptyView.setVisibility(View.GONE);
        }
        recyclerView.setVisibility(View.GONE);
    }

    private void loadCategoryData() {
        if (categoryName == null || categoryName.isEmpty()) {
            if (loadingView != null) {
                loadingView.setVisibility(View.GONE);
            }
            showEmptyView("暂无分类数据");
            return;
        }

        List<IdleData> data = ObectManager.queryCategoryAll(categoryName);
        categoryDataList = data != null ? data : new ArrayList<>();

        // 同步过滤无效数据
        categoryDataList.removeIf(idleData ->
                idleData == null || idleData.getPreviewUrl400() == null || idleData.getPreviewUrl400().isEmpty()
        );

        // 同步更新UI
        if (loadingView != null) {
            loadingView.setVisibility(View.GONE);
        }

        if (categoryDataList.isEmpty()) {
            showEmptyView("暂无" + categoryName + "分类内容");
            recyclerView.setVisibility(View.GONE);
        } else {
            if (emptyView != null) {
                emptyView.setVisibility(View.GONE);
            }
            recyclerView.setVisibility(View.VISIBLE);
            categoryAdapter.setDataInfo(categoryDataList); // 同步设置数据
        }
    }

    private void showEmptyView(String tipText) {
        if (emptyView == null) return;
        emptyView.setVisibility(View.VISIBLE);
        emptyView.setText(tipText);
    }

    @Override
    public void onItemClickAction(IdleData info) {
        if (!isAdded() || info == null) return;
        Intent intent = new Intent(requireActivity(), IdleWallActivity.class);
        intent.putExtra(Comutils.key_info, info);
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 清理资源
        categoryDataList = null;
        categoryAdapter = null;
        recyclerView = null;
        loadingView = null;
        emptyView = null;
    }
}