package com.gallery.free.wallpaper.fragment

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gallery.free.wallpaper.DetailwpActivity
import com.gallery.free.wallpaper.R
import com.gallery.free.wallpaper.StaggeredGridSpacingItemDecoration
import com.gallery.free.wallpaper.WpAdapter
import com.gallery.free.wallpaper.WpItem
import com.gallery.free.wallpaper.database.FavorWpDbHelper
import com.gallery.free.wallpaper.database.FavorWpManager
import com.gallery.free.wallpaper.databinding.FragmentColleBinding

class ColleFragment : Fragment() {

    private var _binding: FragmentColleBinding? = null
    private val binding get() = _binding!!
    private lateinit var favoriteManager: FavorWpManager
    private var adapter: WpAdapter? = null
    private var currentFavoriteInfos: List<FavorWpDbHelper.FavoriteInfo> = emptyList()

    // 存储当前显示的壁纸项列表
    private var currentWallpaperItems: List<WpItem> = emptyList()

    // 添加广播接收器
    private val favoriteChangeReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                DetailwpActivity.Companion.ACTION_FAVORITE_CHANGED -> {
                    Log.d("CollectionFragment", "收到收藏变更广播")
                    activity?.runOnUiThread {
                        refreshDataFromDatabase()
                    }
                }
            }
        }
    }

    companion object {
        fun newInstance(): ColleFragment {
            return ColleFragment()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentColleBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化数据库管理
        favoriteManager = FavorWpManager.Companion.getInstance(requireContext())

        // 注册广播接收器
        registerFavoriteChangeReceiver()

        setupWallpaperGrid()
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun registerFavoriteChangeReceiver() {
        val filter = IntentFilter(DetailwpActivity.Companion.ACTION_FAVORITE_CHANGED)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requireActivity().registerReceiver(favoriteChangeReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
        } else {
            requireActivity().registerReceiver(favoriteChangeReceiver, filter)
        }
    }

    private fun unregisterFavoriteChangeReceiver() {
        try {
            requireActivity().unregisterReceiver(favoriteChangeReceiver)
        } catch (e: IllegalArgumentException) {
            // 如果接收器未注册，忽略异常
        }
    }

    private fun setupWallpaperGrid() {
        // 获取收藏列表（包含详细信息）
        val newFavoriteInfos = favoriteManager.getAllFavoritesWithInfo()

        // 检查是否有变化，没有变化则不重新加载
        if (newFavoriteInfos == currentFavoriteInfos && adapter != null) {
            Log.d("CollectionFragment", "收藏无变化，跳过重新加载")
            return
        }

        currentFavoriteInfos = newFavoriteInfos
        updateFavoriteCount(newFavoriteInfos.size)

        if (newFavoriteInfos.isEmpty()) {
            showEmptyState()
        } else {
            showWallpaperGrid(newFavoriteInfos)
        }
    }

    private fun getLikedWallpapers(favoriteInfos: List<FavorWpDbHelper.FavoriteInfo>): List<WpItem> {
        // 创建完整的 WpItem 对象列表
        val wallpaperItems = favoriteInfos.map { info ->
            // 使用描述，如果描述为空则使用默认文本
            val displayDescription = if (info.description.isNotEmpty()) {
                info.description
            } else {
                "Collected Wallpaper"
            }

            // 创建完整的 WpItem 对象
            // 注意：收藏的壁纸只有完整的URL，所以smallUrl和fullUrl使用相同的URL
            WpItem(
                smallUrl = info.imageUrl,
                fullUrl = info.imageUrl,
                description = displayDescription
            )
        }

        // 存储当前显示的壁纸项
        currentWallpaperItems = wallpaperItems

        return wallpaperItems
    }

    // 更新收藏数量显示
    private fun updateFavoriteCount(count: Int) {
        if (count > 0) {
            binding.textFavoriteCount.text = "$count photo collected"
            binding.textFavoriteCountContainer.visibility = View.VISIBLE
        } else {
            binding.textFavoriteCountContainer.visibility = View.GONE
        }
    }

    private fun showEmptyState() {
        val emptyLayout = binding.root.findViewById<View>(R.id.empty_likes_layout)
        emptyLayout?.visibility = View.VISIBLE

        binding.wallpaperRecyclerView.visibility = View.GONE
        binding.textFavoriteCountContainer.visibility = View.GONE
    }

    private fun showWallpaperGrid(favoriteInfos: List<FavorWpDbHelper.FavoriteInfo>) {
        val emptyLayout = binding.root.findViewById<View>(R.id.empty_likes_layout)
        emptyLayout?.visibility = View.GONE

        binding.wallpaperRecyclerView.visibility = View.VISIBLE

        val wallpaperList = getLikedWallpapers(favoriteInfos)

        // 使用StaggeredGridLayoutManager瀑布流，每行2列
        val spanCount = 2
        val layoutManager = StaggeredGridLayoutManager(
            spanCount,
            StaggeredGridLayoutManager.VERTICAL
        )

        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE

        // 只在第一次或布局管理器为空时设置
        if (binding.wallpaperRecyclerView.layoutManager == null) {
            binding.wallpaperRecyclerView.layoutManager = layoutManager

            // 使用StaggeredGridSpacingItemDecoration来设置间距
            val spacingInPixels = resources.getDimensionPixelSize(R.dimen.grid_spacing)
            binding.wallpaperRecyclerView.addItemDecoration(
                StaggeredGridSpacingItemDecoration(spanCount, spacingInPixels)
            )
        }

        // 传递 WpItem 对象列表，而不是URL列表
        adapter = WpAdapter(wallpaperList) { position, wallpaper ->
            // 检查是否有数据
            if (currentWallpaperItems.isEmpty()) return@WpAdapter

            // 获取所有壁纸的完整 WpItem 列表
            val intent = Intent(requireContext(), DetailwpActivity::class.java).apply {
                putExtra("wallpaper_url", wallpaper.fullUrl)
                putExtra("wallpaper_description", wallpaper.description)
                // 传递完整的 WpItem 列表
                putParcelableArrayListExtra("wallpaper_item_list", ArrayList(currentWallpaperItems))
                putExtra("current_position", position)
            }
            startActivity(intent)
            requireActivity().overridePendingTransition(
                android.R.anim.fade_in,
                android.R.anim.fade_out
            )
        }
        binding.wallpaperRecyclerView.adapter = adapter
    }

    override fun onResume() {
        super.onResume()
        Log.d("CollectionFragment", "onResume 调用")

        // 只检查是否有变化，不强制重新加载
        val newFavoriteInfos = favoriteManager.getAllFavoritesWithInfo()

        if (newFavoriteInfos != currentFavoriteInfos) {
            Log.d("CollectionFragment", "收藏有变化，重新加载")
            // 如果收藏有变化，才重新加载
            currentFavoriteInfos = newFavoriteInfos
            updateFavoriteCount(newFavoriteInfos.size)

            if (newFavoriteInfos.isEmpty()) {
                showEmptyState()
            } else {
                showWallpaperGrid(newFavoriteInfos)
            }
        } else {
            Log.d("CollectionFragment", "onResume 中收藏无变化")
        }
    }

    // 直接从数据库刷新数据的方法
    private fun refreshDataFromDatabase() {
        Log.d("CollectionFragment", "从数据库刷新数据")
        val newFavoriteInfos = favoriteManager.getAllFavoritesWithInfo()

        // 即使没有变化也强制更新UI，确保数据同步
        currentFavoriteInfos = newFavoriteInfos
        updateFavoriteCount(newFavoriteInfos.size)

        if (newFavoriteInfos.isEmpty()) {
            showEmptyState()
        } else {
            showWallpaperGrid(newFavoriteInfos)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        // 注销广播接收器
        unregisterFavoriteChangeReceiver()

        // 清除适配器和数据
        adapter = null
        binding.wallpaperRecyclerView.adapter = null
        currentWallpaperItems = emptyList()  // 清理数据

        _binding = null
    }
}