package com.gallery.free.wallpaper.fragment

import android.R
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gallery.free.wallpaper.DetailwpActivity
import com.gallery.free.wallpaper.MyApplication
import com.gallery.free.wallpaper.StaggeredGridSpacingItemDecoration
import com.gallery.free.wallpaper.Utils_json
import com.gallery.free.wallpaper.WpAdapter
import com.gallery.free.wallpaper.WpItem
import com.gallery.free.wallpaper.databinding.FragmentWpgridBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class WpGridFragment : Fragment() {

    private var _binding: FragmentWpgridBinding? = null
    private val binding get() = _binding!!
    private lateinit var category: String
    private var wallpaperList: List<WpItem> = emptyList()
    private var adapter: WpAdapter? = null

    // 滚动监听回调
    private var scrollListener: ((Boolean) -> Unit)? = null

    // 添加协程作用域
    private val fragmentScope = CoroutineScope(Dispatchers.Main + Job())

    companion object {
        private const val ARG_CATEGORY = "category"
        private const val TAG = "WallpaperGridFragment"

        fun newInstance(category: String): WpGridFragment {
            val fragment = WpGridFragment()
            val args = Bundle()
            args.putString(ARG_CATEGORY, category)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            category = it.getString(ARG_CATEGORY, "Film")
        }
    }

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

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

    // 设置滚动监听回调
    fun setOnScrollListener(listener: (Boolean) -> Unit) {
        this.scrollListener = listener
    }

    fun checkCurrentScrollState() {
        if (!isAdded || _binding == null) {
            // Fragment 未附加或绑定为null，直接返回
            scrollListener?.invoke(false)
            return
        }

        try {
            val canScrollUp = binding.wallpaperRecyclerView.canScrollVertically(-1)
            Log.d(TAG, "checkCurrentScrollState: canScrollUp = $canScrollUp")
            scrollListener?.invoke(canScrollUp)
        } catch (e: Exception) {
            e.printStackTrace()
            scrollListener?.invoke(false)
        }
    }

    // 刷新壁纸
    fun refreshWallpapers(onComplete: () -> Unit) {
        fragmentScope.launch {
            try {
                if (!isAdded || _binding == null) {
                    onComplete()
                    return@launch
                }

                // 使用 Application 获取数据
                val fileName = when (category) {
                    "Film" -> "Film_two.json"
                    "Nature" -> "Nature_two.json"
                    "Travel" -> "Travel_two.json"
                    else -> "Film_two.json"
                }

                val myApp = activity?.application as? MyApplication
                if (myApp != null) {
                    // 从 Application 缓存获取数据
                    val wallpaperItems = withContext(Dispatchers.IO) {
                        try {
                            myApp.getWallpaperItems(fileName)
                        } catch (e: Exception) {
                            // 如果缓存失败，回退到原始方法
                            Log.w(TAG, "从缓存获取数据失败，回退到原始方法", e)
                            val wallpaperJsonList = Utils_json.loadWallpapersFromAssets(requireContext(), fileName)
                            wallpaperJsonList.map { json ->
                                Utils_json.convertToWallpaperItem(json)
                            }
                        }
                    }

                    if (wallpaperItems.isEmpty()) {
                        showErrorState()
                        onComplete()
                        return@launch
                    }

                    wallpaperList = wallpaperItems

                    // 重新打乱壁纸顺序
                    val shuffledList = wallpaperList.shuffled()

                    val newAdapter = WpAdapter(shuffledList) { position: Int, wallpaper: WpItem ->
                        if (!isAdded) return@WpAdapter

                        val intent = Intent(requireContext(), DetailwpActivity::class.java).apply {
                            putExtra("wallpaper_url", wallpaper.fullUrl)
                            putExtra("wallpaper_description", wallpaper.description)
                            // 传递完整的WpItem列表
                            putParcelableArrayListExtra(
                                "wallpaper_item_list",
                                ArrayList(shuffledList)
                            )
                            putExtra("current_position", position)
                        }
                        startActivity(intent)
                        requireActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                    }

                    // 更新适配器
                    binding.wallpaperRecyclerView.adapter = newAdapter
                    adapter = newAdapter

                    // 检查滚动状态
                    checkCurrentScrollState()

                    onComplete()
                } else {
                    // Application 不可用，使用原始方法
                    loadWallpapersWithOriginalMethod(onComplete)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                if (isAdded && _binding != null) {
                    showErrorState()
                }
                onComplete()
            }
        }
    }

    // 使用原始方法加载壁纸（兼容性回退）
    private fun loadWallpapersWithOriginalMethod(onComplete: () -> Unit) {
        Handler(Looper.getMainLooper()).postDelayed({
            try {
                if (!isAdded || _binding == null) {
                    onComplete()
                    return@postDelayed
                }

                val fileName = when (category) {
                    "Film" -> "Film_two.json"
                    "Nature" -> "Nature_two.json"
                    "Travel" -> "Travel_two.json"
                    else -> "Film_two.json"
                }

                val wallpaperJsonList = Utils_json.loadWallpapersFromAssets(requireContext(), fileName)
                if (wallpaperJsonList.isEmpty()) {
                    showErrorState()
                    onComplete()
                    return@postDelayed
                }

                wallpaperList = wallpaperJsonList.map { json ->
                    Utils_json.convertToWallpaperItem(json)
                }

                // 重新打乱壁纸顺序
                val shuffledList = wallpaperList.shuffled()

                val newAdapter = WpAdapter(shuffledList) { position: Int, wallpaper: WpItem ->
                    if (!isAdded) return@WpAdapter

                    val intent = Intent(requireContext(), DetailwpActivity::class.java).apply {
                        putExtra("wallpaper_url", wallpaper.fullUrl)
                        putExtra("wallpaper_description", wallpaper.description)
                        // 传递完整的WpItem列表
                        putParcelableArrayListExtra("wallpaper_item_list", ArrayList(shuffledList))
                        putExtra("current_position", position)
                    }
                    startActivity(intent)
                    requireActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }

                // 更新适配器
                binding.wallpaperRecyclerView.adapter = newAdapter
                adapter = newAdapter

                checkCurrentScrollState()
                onComplete()
            } catch (e: Exception) {
                e.printStackTrace()
                if (isAdded && _binding != null) {
                    showErrorState()
                }
                onComplete()
            }
        }, 1000)
    }

    // 回到顶部
    fun scrollToTop() {
        if (!isAdded || _binding == null) return

        try {
            binding.wallpaperRecyclerView.smoothScrollToPosition(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setupWallpaperGrid() {
        fragmentScope.launch {
            try {
                val fileName = when (category) {
                    "Film" -> "Film_two.json"
                    "Nature" -> "Nature_two.json"
                    "Travel" -> "Travel_two.json"
                    else -> "Film_two.json"
                }

                // 使用 Application 获取数据
                val myApp = activity?.application as? MyApplication
                val wallpaperItems = if (myApp != null) {
                    // 从 Application 缓存获取数据
                    withContext(Dispatchers.IO) {
                        try {
                            myApp.getWallpaperItems(fileName)
                        } catch (e: Exception) {
                            // 如果缓存失败，回退到原始方法
                            Log.w(TAG, "从缓存获取数据失败，回退到原始方法", e)
                            val wallpaperJsonList = Utils_json.loadWallpapersFromAssets(requireContext(), fileName)
                            wallpaperJsonList.map { json ->
                                Utils_json.convertToWallpaperItem(json)
                            }
                        }
                    }
                } else {
                    // Application 不可用，使用原始方法
                    val wallpaperJsonList = Utils_json.loadWallpapersFromAssets(requireContext(), fileName)
                    wallpaperJsonList.map { json ->
                        Utils_json.convertToWallpaperItem(json)
                    }
                }

                if (wallpaperItems.isEmpty()) {
                    showErrorState()
                    return@launch
                }

                wallpaperList = wallpaperItems
                val shuffledList = wallpaperList.shuffled()

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

                // 设置间距均匀
                layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE

                binding.wallpaperRecyclerView.layoutManager = layoutManager

                val spacingInPixels = resources.getDimensionPixelSize(com.gallery.free.wallpaper.R.dimen.grid_spacing)
                binding.wallpaperRecyclerView.addItemDecoration(
                    StaggeredGridSpacingItemDecoration(spanCount, spacingInPixels)
                )

                adapter = WpAdapter(shuffledList) { position: Int, wallpaper: WpItem ->
                    if (!isAdded) return@WpAdapter

                    val intent = Intent(requireContext(), DetailwpActivity::class.java).apply {
                        putExtra("wallpaper_url", wallpaper.fullUrl)  // 传递全尺寸URL
                        putExtra("wallpaper_description", wallpaper.description)  // 传递描述
                        putParcelableArrayListExtra("wallpaper_item_list", ArrayList(shuffledList))
                        putExtra("current_position", position)
                    }
                    startActivity(intent)
                    requireActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }
                binding.wallpaperRecyclerView.adapter = adapter

                // 设置滚动监听
                setupScrollListener()

                // 初始检查滚动状态
                binding.wallpaperRecyclerView.post {
                    checkCurrentScrollState()
                }
            } catch (e: Exception) {
                Log.e(TAG, "设置壁纸网格失败", e)
                showErrorState()
            }
        }
    }

    private fun setupScrollListener() {
        binding.wallpaperRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 检查 Fragment 是否仍然有效
                if (!isAdded || _binding == null) return

                try {
                    val canScrollUp = recyclerView.canScrollVertically(-1)
                    Log.d(TAG, "onScrolled: canScrollUp = $canScrollUp, dy = $dy")
                    scrollListener?.invoke(canScrollUp)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (!isAdded || _binding == null) return

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    try {
                        val canScrollUp = recyclerView.canScrollVertically(-1)
                        Log.d(TAG, "scroll state changed: canScrollUp = $canScrollUp")
                        scrollListener?.invoke(canScrollUp)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }

    private fun showErrorState() {
        if (isAdded) {
            Toast.makeText(requireContext(), "加载失败...", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清除滚动监听回调
        scrollListener = null
        _binding = null
        adapter = null

        // 取消所有协程
        fragmentScope.coroutineContext.cancelChildren()
    }
}