package com.gallery.free.wallpaper.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.gallery.free.wallpaper.HoPagerAdapter
import com.gallery.free.wallpaper.MyApplication
import com.gallery.free.wallpaper.MyApplication.Companion.FIXED_CATEGORIES
import com.gallery.free.wallpaper.R
import com.gallery.free.wallpaper.databinding.FragmentHoBinding
import com.google.android.material.tabs.TabLayoutMediator
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 HoFragment : Fragment() {

    private var _binding: FragmentHoBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewPager: ViewPager2
    private lateinit var pagerAdapter: HoPagerAdapter

    private var currentViewPagerPosition = 0
    private val VIEW_PAGER_POSITION_KEY = "view_pager_position"

    // 刷新状态
    private var isRefreshing = false

    // 添加协程作用域
    private val fragmentScope = CoroutineScope(Dispatchers.Main + Job())
    private var categories: List<String> = FIXED_CATEGORIES

    companion object {
        private const val TAG = "HomeFragment"

        fun newInstance(): HoFragment {
            return HoFragment()
        }
    }

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

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

        // 恢复状态
        savedInstanceState?.let {
            currentViewPagerPosition = it.getInt(VIEW_PAGER_POSITION_KEY, 0)
        }

        // 先异步加载分类数据
        loadCategoriesAndSetupUI()
    }

    /**
     * 异步加载分类数据并设置UI
     */
    private fun loadCategoriesAndSetupUI() {
        fragmentScope.launch {
            try {
                // 使用固定分类
                categories = FIXED_CATEGORIES
                Log.d(TAG, "使用固定分类: $categories")

                // 初始化 ViewPager 和适配器
                setupViewPager()
                setupTabs()

            } catch (e: Exception) {
                Log.e(TAG, "初始化分类失败，使用默认分类", e)
                categories = FIXED_CATEGORIES
                setupViewPager()
                setupTabs()
            }

            // 设置按钮和状态
            setupRefreshButton()
            setupScrollToTopButton()

            binding.viewPager.post {
                if (currentViewPagerPosition > 0 && _binding != null) {
                    binding.viewPager.setCurrentItem(currentViewPagerPosition, false)
                }
                updateScrollToTopButton()
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt(VIEW_PAGER_POSITION_KEY, binding.viewPager.currentItem)
    }

    private fun setupViewPager() {
        // 传递分类列表给适配器
        pagerAdapter = HoPagerAdapter(this, categories)
        viewPager = binding.viewPager
        viewPager.adapter = pagerAdapter
        viewPager.offscreenPageLimit = 2

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentViewPagerPosition = position
                animateTabSelection(position)
                // 切换标签页时更新滚动状态
                updateScrollToTopButton()

                // 异步预加载相邻页面的数据
                preloadAdjacentPages(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    updateScrollToTopButton()
                }
            }
        })
    }

    /**
     * 预加载相邻页面的数据
     */
    private fun preloadAdjacentPages(currentPosition: Int) {
        val myApp = requireActivity().application as? MyApplication ?: return

        fragmentScope.launch {
            try {
                // 预加载前一个页面
                if (currentPosition > 0) {
                    val prevCategory = categories[currentPosition - 1]
                    val prevFileName = "${prevCategory}_two.json"
                    withContext(Dispatchers.IO) {
                        myApp.getWallpaperItems(prevFileName)
                    }
                }

                // 预加载后一个页面
                if (currentPosition < categories.size - 1) {
                    val nextCategory = categories[currentPosition + 1]
                    val nextFileName = "${nextCategory}_two.json"
                    withContext(Dispatchers.IO) {
                        myApp.getWallpaperItems(nextFileName)
                    }
                }
            } catch (e: Exception) {
                Log.w(TAG, "预加载相邻页面数据失败", e)
            }
        }
    }

    private fun setupTabs() {
        val tabLayout = binding.tabLayout
        val tabTitles = categories.toTypedArray()

        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = tabTitles[position]
        }.attach()

        // 初始选中第一个标签
        animateTabSelection(currentViewPagerPosition)
    }

    private fun setupRefreshButton() {
        binding.btnRefresh.setOnClickListener {
            if (!isRefreshing) {
                startRefresh()
            }
        }
    }

    private fun setupScrollToTopButton() {
        binding.btnScrollToTop.setOnClickListener {
            scrollToTop()
        }
        binding.btnScrollToTop.visibility = View.GONE
    }

    private fun startRefresh() {
        isRefreshing = true
        binding.btnRefresh.isEnabled = false

        startRefreshAnimation()

        // 获取当前 Fragment 并刷新
        val currentFragment = getCurrentFragment()
        if (currentFragment != null) {
            Log.d(TAG, "开始刷新，当前Fragment: $currentFragment")
            currentFragment.refreshWallpapers {
                stopRefresh()
            }
        } else {
            Log.w(TAG, "获取不到当前Fragment，无法刷新")
            stopRefresh()
        }
    }

    private fun stopRefresh() {
        isRefreshing = false
        if (_binding != null) {
            binding.btnRefresh.isEnabled = true
        }
        stopRefreshAnimation()
    }

    private fun startRefreshAnimation() {
        if (_binding != null) {
            binding.btnRefresh.setImageResource(R.drawable.loading_animation)
        }
        Log.d(TAG, "开始刷新动画")
    }

    private fun stopRefreshAnimation() {
        if (_binding != null) {
            binding.btnRefresh.setImageResource(R.drawable.ic_refreshit)
        }
        Log.d(TAG, "停止刷新动画")
    }

    private fun scrollToTop() {
        val currentFragment = getCurrentFragment()
        if (currentFragment != null) {
            Log.d(TAG, "滚动到顶部，当前Fragment: $currentFragment")
            currentFragment.scrollToTop()
            // 隐藏回到顶部按钮
            if (_binding != null) {
                binding.btnScrollToTop.visibility = View.GONE
            }
        } else {
            Log.w(TAG, "获取不到当前Fragment，无法滚动到顶部")
        }
    }

    private fun getCurrentFragment(): WpGridFragment? {
        if (!isAdded || _binding == null) return null

        return try {
            // 通过适配器获取当前 Fragment
            val fragment = pagerAdapter.getFragment(viewPager.currentItem)
            if (fragment == null) {
                Log.w(TAG, "通过适配器获取Fragment失败，尝试备用方法")
                // 备用方法：通过ViewPager的当前项获取Fragment
                val fragmentTag = "f${viewPager.currentItem}"
                childFragmentManager.findFragmentByTag(fragmentTag) as? WpGridFragment
            } else {
                fragment
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "获取Fragment异常: ${e.message}")
            null
        }
    }

    private fun updateScrollToTopButton() {
        // 检查绑定是否有效
        if (!isAdded || _binding == null) {
            Log.d(TAG, "HomeFragment 未附加或绑定为空，跳过更新滚动按钮")
            return
        }

        val currentFragment = getCurrentFragment()
        if (currentFragment != null) {
            Log.d(TAG, "更新滚动按钮状态，当前Fragment: $currentFragment")
            currentFragment.setOnScrollListener { canScrollUp ->
                // 再次检查绑定是否仍然有效
                if (!isAdded || _binding == null) return@setOnScrollListener

                val shouldShowButton = canScrollUp
                binding.btnScrollToTop.visibility = if (shouldShowButton) View.VISIBLE else View.GONE

                Log.d(TAG, "滚动状态改变: canScrollUp = $canScrollUp, 按钮可见性 = ${if (shouldShowButton) "VISIBLE" else "GONE"}")
            }
            currentFragment.checkCurrentScrollState()
        } else {
            binding.btnScrollToTop.visibility = View.GONE
            Log.w(TAG, "获取不到当前Fragment，隐藏回到顶部按钮")
        }
    }

    private fun animateTabSelection(position: Int) {
        if (!isAdded || _binding == null) return

        val tabCount = binding.tabLayout.tabCount

        for (i in 0 until tabCount) {
            val tab = binding.tabLayout.getTabAt(i)
            val tabView = tab?.view

            if (i == position) {
                tabView?.animate()
                    ?.scaleX(1.1f)
                    ?.scaleY(1.1f)
                    ?.setDuration(200)
                    ?.setInterpolator(OvershootInterpolator())
                    ?.start()
            } else {
                tabView?.animate()
                    ?.scaleX(1.0f)
                    ?.scaleY(1.0f)
                    ?.setDuration(150)
                    ?.start()
            }
        }

        updateScrollToTopButton()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopRefreshAnimation()
        _binding = null

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