package com.snap.wall.fragment;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.snap.wall.R;
import com.snap.wall.RecentWallpaperManager;
import com.snap.wall.RecentWallpaperAdapter;
import com.snap.wall.Wallpaper;
import com.snap.wall.activity.PreviewActivity;
import com.snap.wall.bean.Information;

import java.util.List;

public class RecentWallpaperFragment extends Fragment {
    private GridView gvRecent;
    private TextView tvEmpty;
    private RequestManager glideRequestManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recent_wallpaper, container, false);
        gvRecent = view.findViewById(R.id.gv_recent_wallpapers);
        tvEmpty = view.findViewById(R.id.tv_empty);
        glideRequestManager = Glide.with(this);

        if (gvRecent == null) {
            TextView errorTv = new TextView(requireContext());
            errorTv.setText("Failed to load control");
            errorTv.setTextSize(16);
            errorTv.setPadding(20, 20, 20, 20);
            return errorTv;
        }

        loadRecentWallpapers();
        return view;
    }

    private void loadRecentWallpapers() {
        // 核心校验：Fragment是否已销毁
        if (isDetached() || requireContext() == null || gvRecent == null) return;

        List<Wallpaper> wallpaperList = RecentWallpaperManager.getInstance(requireContext()).getRecentWallpapers();
        if (wallpaperList.isEmpty()) {
            gvRecent.setVisibility(View.GONE);
            if (tvEmpty != null) {
                tvEmpty.setVisibility(View.VISIBLE);
                tvEmpty.setText("No recent browsing history");
            }
            return;
        }

        gvRecent.setVisibility(View.VISIBLE);
        if (tvEmpty != null) tvEmpty.setVisibility(View.GONE);

        // 初始化适配器（传递Glide请求管理器）
        RecentWallpaperAdapter adapter = new RecentWallpaperAdapter(requireContext(), wallpaperList, glideRequestManager, wallpaper -> {
            // 跳转前校验Fragment状态
            if (!isDetached()) {
                gotoDetailPage(wallpaper);
            }
        });
        gvRecent.setAdapter(adapter);
        gvRecent.setClickable(false);
        gvRecent.setFocusable(false);
    }

    // 跳转到详情页
    private void gotoDetailPage(Wallpaper wallpaper) {
        Information data = new Information();
        data.setImId(wallpaper.getId());
        data.setFullUrl(wallpaper.getImageUrl());
        data.setDescription(wallpaper.getTitle());
        data.setPreviewUrl1080(wallpaper.getImageUrl());

        Intent intent = new Intent(requireContext(), PreviewActivity.class);
        intent.putExtra("key_info", data);
        startActivity(intent);
    }

    // Fragment销毁时清理Glide请求（修正方法名错误）
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (glideRequestManager != null) {
            // 正确的Glide请求清理方法
            glideRequestManager.pauseRequests(); // 暂停所有请求
            glideRequestManager.clear(gvRecent); // 清除GridView中所有图片请求
        }
        gvRecent = null;
        tvEmpty = null;
        glideRequestManager = null;
    }
}