package com.idle.wall.idlefragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.idle.wall.R;
import com.idle.wall.ItemPageAdapter;
import com.idle.wall.idleactivity.IdleLikeActivity;
import com.idle.wall.idleactivity.IdleMainActivity;
import com.idle.wall.idleactivity.IdleRecentActivity;
import com.idle.wall.idleadapter.OnLikelist;
import com.idle.wall.idleadapter.OnViewList; // 新增：浏览数据监听接口
import com.idle.wall.idlebean.IdleData;
import com.idle.wall.idleitem.ItemIdlePage;
import com.idle.wall.idletool.ObectManager;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.objectbox.reactive.DataSubscription;

public class FragmentIdlePage extends Fragment {
    private RecyclerView recyclerView;
    private ItemPageAdapter adapter;
    private List<ItemIdlePage> itemList;
    private List<IdleData> likeDataList;
    private List<IdleData> viewDataList;
    private DataSubscription likeDataSubscription;
    private DataSubscription viewDataSubscription;
    private final ExecutorService dbExecutor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    private boolean isRefreshing = false;
    private static final long REFRESH_THROTTLE_MS = 500;

    public FragmentIdlePage() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_idle_page, container, false);
        recyclerView = view.findViewById(R.id.page_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        likeDataList = new ArrayList<>();
        viewDataList = new ArrayList<>(); // 初始化浏览数据
        initData();

        // 初始化适配器
        adapter = new ItemPageAdapter(getContext(), itemList, item -> handleItemClick(item));
        recyclerView.setAdapter(adapter);

        // 隐藏加载中
        View loadingView = view.findViewById(R.id.loading_page);
        if (loadingView != null) {
            loadingView.setVisibility(View.GONE);
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        registerLikeDataListener();
        registerViewDataListener();
        queryLikeDataAsync();
        queryViewDataAsync(); // 新增
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterLikeDataListener();
        unregisterViewDataListener(); // 新增
        isRefreshing = false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterLikeDataListener();
        unregisterViewDataListener();
        dbExecutor.shutdown();
        mainHandler.removeCallbacksAndMessages(null);
        likeDataList = null;
        viewDataList = null;
        itemList = null;
        adapter = null;
    }
    private void queryLikeDataAsync() {
        dbExecutor.execute(() -> {
            List<IdleData> data = ObectManager.getLikeList();
            mainHandler.post(() -> {
                likeDataList = data != null ? data : new ArrayList<>();
                refreshLikeItemImage();
            });
        });
    }

    private void registerLikeDataListener() {
        if (likeDataSubscription != null) return;

        likeDataSubscription = ObectManager.setLikeDataListener(new OnLikelist() {
            @Override
            public void onLikeList(List<IdleData> data) {
                if (isRefreshing) return;
                isRefreshing = true;

                likeDataList = data != null ? data : new ArrayList<>();
                refreshLikeItemImage();

                mainHandler.postDelayed(() -> isRefreshing = false, REFRESH_THROTTLE_MS);
            }
        });
    }

    private void unregisterLikeDataListener() {
        if (likeDataSubscription != null) {
            likeDataSubscription.cancel();
            likeDataSubscription = null;
        }
    }

    private void refreshLikeItemImage() {
        if (itemList == null || itemList.isEmpty() || adapter == null) return;

        ItemIdlePage likeItem = itemList.get(0);
        String newImageUrl = getLikeImageUrl();

        if (!newImageUrl.equals(likeItem.getImageUrl())) {
            likeItem.setImageUrl(newImageUrl);
            adapter.notifyItemChanged(0, "UPDATE_IMAGE");
        }
    }

    private String getLikeImageUrl() {
        if (!likeDataList.isEmpty()) {
            IdleData first = likeDataList.get(0);
            String url = first.getPreviewUrl400();
            return (url != null && !url.isEmpty()) ? url : getDefaultImageUrl();
        }
        return getDefaultImageUrl();
    }
    private void queryViewDataAsync() {
        dbExecutor.execute(() -> {
            List<IdleData> data = ObectManager.getViewList();
            mainHandler.post(() -> {
                viewDataList = data != null ? data : new ArrayList<>();
                refreshViewItemImage();
            });
        });
    }


    private void registerViewDataListener() {
        if (viewDataSubscription != null) return;

        viewDataSubscription = ObectManager.setViewDataListener(new OnViewList() {
            @Override
            public void onViewList(List<IdleData> data) {
                if (isRefreshing) return;
                isRefreshing = true;

                viewDataList = data != null ? data : new ArrayList<>();
                refreshViewItemImage();

                mainHandler.postDelayed(() -> isRefreshing = false, REFRESH_THROTTLE_MS);
            }
        });
    }
    private void unregisterViewDataListener() {
        if (viewDataSubscription != null) {
            viewDataSubscription.cancel();
            viewDataSubscription = null;
        }
    }
    private void refreshViewItemImage() {
        if (itemList == null || itemList.size() < 2 || adapter == null) return;

        ItemIdlePage viewItem = itemList.get(1);
        String newImageUrl = getViewImageUrl();

        if (!newImageUrl.equals(viewItem.getImageUrl())) {
            viewItem.setImageUrl(newImageUrl);
            adapter.notifyItemChanged(1, "UPDATE_IMAGE");
        }
    }
    private String getViewImageUrl() {
        if (!viewDataList.isEmpty()) {
            IdleData latestView = viewDataList.get(0);
            String url = latestView.getPreviewUrl400();
            return (url != null && !url.isEmpty()) ? url : getDefaultImageUrl();
        }
        return getDefaultImageUrl();
    }
    private String getDefaultImageUrl() {
        return "local_placeholder";
    }
    private void initData() {
        itemList = new ArrayList<>();
        itemList.add(new ItemIdlePage(getDefaultImageUrl(), getString(R.string.like_page_title)));
        itemList.add(new ItemIdlePage(getDefaultImageUrl(), getString(R.string.Recently)));

    }

    private void handleItemClick(ItemIdlePage item) {
        if (getActivity() == null) return;
        String itemName = item.getName();
        if (getString(R.string.like_page_title).equals(itemName)) {
            IdleLikeActivity.startLikeActivity((IdleMainActivity) getActivity());
        } else if (getString(R.string.Recently).equals(itemName)) {
            startActivity(new Intent(getActivity(), IdleRecentActivity.class));

        }
    }
}