package com.app.input.personalised.board.boartfragment

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.app.input.personalised.board.BoartApp
import com.app.input.personalised.board.R
import com.app.input.personalised.board.databean.KeyboardTheme
import com.app.input.personalised.board.databean.ThemeCategory
import com.app.input.personalised.board.databinding.FragmentHomeBinding
import com.app.input.personalised.board.listhelpers.BannerListAdapter
import com.app.input.personalised.board.listhelpers.RecommendedGridAdapter
import com.app.input.personalised.board.boartactivity.ThemeDetailActivity
import com.app.input.personalised.board.boartactivity.ThemeSearchActivity

class HomeFragment : Fragment() {

    private lateinit var vb: FragmentHomeBinding
    private lateinit var bannerListAdapter: BannerListAdapter
    private lateinit var recommendedGridAdapter: RecommendedGridAdapter
    
    private var viewAllList: MutableList<ThemeCategory> = mutableListOf()
    private var bannerList: MutableList<KeyboardTheme> = mutableListOf()
    private var currentStaggeredList: MutableList<KeyboardTheme> = mutableListOf()
    
    private var bannerHandler: Handler? = null
    private var bannerRunnable: Runnable? = null
    private val BANNER_DELAY = 3000L // 3秒
    private var isUserScrolling = false // 用户是否正在滑动
    
    // 懒加载标志，避免重复初始化
    private var isDataInitialized = false

    companion object {
        @JvmStatic
        fun newInstance() = HomeFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vb = FragmentHomeBinding.inflate(layoutInflater)
        return vb.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 只初始化最轻量级的内容
        if (!isDataInitialized) {
            initSearchBar() // 先初始化最简单的
            isDataInitialized = true
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 在 onResume 时才加载数据，此时 Fragment 已经可见
        if (isDataInitialized && viewAllList.isEmpty()) {
            initData()
            // ViewPager2 延迟加载，确保切换动画完全完成
            val currentView = view
            if (currentView != null) {
                currentView.postDelayed({
                    if (isAdded && !isDetached && currentView.parent != null) {
                        initBanner()
                    }
                }, 200) // 延迟 200ms
                // RecyclerView 延迟更长时间加载，避免阻塞切换
                currentView.postDelayed({
                    if (isAdded && !isDetached && currentView.parent != null) {
                        initStaggeredRecycler()
                    }
                }, 500) // 延迟 500ms，确保切换动画完全完成后再加载
            }
        }
        
        // 确保 banner 已初始化后再启动自动轮播
        if (::bannerListAdapter.isInitialized && !isUserScrolling) {
            startBannerAutoScroll()
        }
    }

    private fun initData() {
        // 检查数据是否已加载
        try {
            val boartAppList = BoartApp.Companion.list
            if (boartAppList.isEmpty()) {
                viewAllList = mutableListOf()
                return
            }
            // 只在需要时创建副本
            viewAllList = boartAppList.toMutableList()
        } catch (e: UninitializedPropertyAccessException) {
            viewAllList = mutableListOf()
            return
        }
        
        // 获取推荐分类
        val recommendList = viewAllList.find { it.parentName == getString(R.string.recommend_name) }
        
        // 获取轮播图数据（从推荐分类中取前5个）
        bannerList = recommendList?.getKeyboardList()?.take(5)?.toMutableList() ?: mutableListOf()
        
        // 瀑布流数据：只使用推荐分类的内容，减少一半数量
        if (recommendList?.getKeyboardList() != null) {
            val fullList = recommendList.getKeyboardList()
            // 只取一半的数据
            val halfSize = fullList.size / 2
            currentStaggeredList = fullList.take(halfSize).toMutableList()
        } else {
            currentStaggeredList = mutableListOf()
        }
    }


    private fun initBanner() {
        if (bannerList.isEmpty()) {
            vb.bannerViewpager.visibility = View.GONE
            vb.bannerIndicator.visibility = View.GONE
            return
        }
        
        bannerListAdapter = BannerListAdapter(requireContext(), bannerList).apply {
            setOnBannerClickListener(object : BannerListAdapter.OnBannerClickListener {
                override fun onBannerClick(beanDetails: KeyboardTheme) {
                    openDetailActivity(beanDetails)
                }
            })
            // 可选：显示标题
            // setShowTitle(true)
        }
        
        vb.bannerViewpager.apply {
            // 设置为 1，最小预加载，减少初始化开销
            offscreenPageLimit = 1
            adapter = bannerListAdapter
            
            // 设置页面间距
            val pageMarginPx = resources.getDimensionPixelOffset(R.dimen.page_margin)
            val nextItemVisiblePx = resources.getDimensionPixelOffset(R.dimen.page_visible)
            val itemDecoration = HorizontalMarginItemDecoration(pageMarginPx, nextItemVisiblePx)
            addItemDecoration(itemDecoration)
            
            // 设置页面切换回调
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    updateBannerIndicator(position)
                }
                
                override fun onPageScrollStateChanged(state: Int) {
                    super.onPageScrollStateChanged(state)
                    when (state) {
                        ViewPager2.SCROLL_STATE_DRAGGING -> {
                            isUserScrolling = true
                            stopBannerAutoScroll()
                        }
                        ViewPager2.SCROLL_STATE_IDLE -> {
                            isUserScrolling = false
                            startBannerAutoScroll()
                        }
                    }
                }
            })
            
            // 添加触摸监听，暂停自动轮播
            setOnTouchListener { _, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                        stopBannerAutoScroll()
                        isUserScrolling = true
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        isUserScrolling = false
                        startBannerAutoScroll()
                    }
                }
                false // 不拦截事件，让ViewPager2正常处理滑动
            }
        }
        
        // 创建指示器
        createBannerIndicators()
        
        // 开始自动轮播
        startBannerAutoScroll()
    }

    private fun createBannerIndicators() {
        vb.bannerIndicator.removeAllViews()
        for (i in bannerList.indices) {
            val indicator = View(context).apply {
                layoutParams = ViewGroup.MarginLayoutParams(
                    resources.getDimensionPixelSize(R.dimen.indicator_width),
                    resources.getDimensionPixelSize(R.dimen.indicator_height)
                ).apply {
                    marginEnd = resources.getDimensionPixelSize(R.dimen.indicator_margin)
                }
                setBackgroundResource(R.drawable.indicator_bg_selector)
                isSelected = i == 0
            }
            vb.bannerIndicator.addView(indicator)
        }
    }

    private fun updateBannerIndicator(position: Int) {
        val realPosition = position % bannerList.size
        for (i in 0 until vb.bannerIndicator.childCount) {
            vb.bannerIndicator.getChildAt(i).isSelected = i == realPosition
        }
    }

    private fun startBannerAutoScroll() {
        if (bannerList.isEmpty() || isUserScrolling) return
        
        stopBannerAutoScroll() // 先清除之前的任务
        
        bannerHandler = Handler(Looper.getMainLooper())
        bannerRunnable = object : Runnable {
            override fun run() {
                if (!isUserScrolling && bannerList.isNotEmpty()) {
                    val currentItem = vb.bannerViewpager.currentItem
                    val nextItem = if (currentItem < bannerList.size - 1) currentItem + 1 else 0
                    vb.bannerViewpager.setCurrentItem(nextItem, true)
                    bannerHandler?.postDelayed(this, BANNER_DELAY)
                }
            }
        }
        bannerHandler?.postDelayed(bannerRunnable!!, BANNER_DELAY)
    }

    private fun stopBannerAutoScroll() {
        bannerRunnable?.let { bannerHandler?.removeCallbacks(it) }
    }

    private fun initStaggeredRecycler() {
        // 大幅减少初始加载的数据量，避免一次性渲染太多
        val initialLoadCount = 10 // 先只加载前10个，大幅减少
        val dataToLoad = if (currentStaggeredList.size > initialLoadCount) {
            currentStaggeredList.take(initialLoadCount).toMutableList()
        } else {
            currentStaggeredList
        }
        
        // 使用RecommendedAdapter（带名称显示）
        recommendedGridAdapter = RecommendedGridAdapter(requireContext()).apply {
            setForYouList(dataToLoad)
        }
        
        vb.staggeredRecycler.apply {
            // 关键设置：在NestedScrollView中使用RecyclerView需要这些配置
            setHasFixedSize(false)
            isNestedScrollingEnabled = false
            // 优化性能：进一步减少缓存大小
            setItemViewCacheSize(5) // 从10减少到5
            // 禁用过度滚动，减少渲染开销
            overScrollMode = View.OVER_SCROLL_NEVER
            
            // 使用GridLayoutManager，和详情页一样
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = recommendedGridAdapter
        }
        
        // 延迟加载剩余数据，避免阻塞主线程
        if (currentStaggeredList.size > initialLoadCount) {
            view?.postDelayed({
                if (isAdded && !isDetached) {
                    // 分批加载，每次加载10个
                    val nextBatch = currentStaggeredList.take(initialLoadCount * 2).toMutableList()
                    recommendedGridAdapter.setForYouList(nextBatch)
                    
                    // 如果还有更多数据，继续延迟加载
                    if (currentStaggeredList.size > initialLoadCount * 2) {
                        view?.postDelayed({
                            if (isAdded && !isDetached) {
                                recommendedGridAdapter.setForYouList(currentStaggeredList)
                            }
                        }, 800) // 再延迟800ms加载完整数据
                    }
                }
            }, 800) // 延迟800ms加载第二批数据
        }
    }

    private fun updateStaggeredData(categoryPosition: Int) {
        // 推荐区域始终显示推荐分类的内容，不受分类切换影响
        val recommendList = viewAllList.find { it.parentName == getString(R.string.recommend_name) }
        if (recommendList != null && recommendList.getKeyboardList() != null) {
            currentStaggeredList = recommendList.getKeyboardList().toMutableList()
            recommendedGridAdapter.setForYouList(currentStaggeredList)
        }
    }

    private fun initSearchBar() {
        vb.tvSearch.setOnClickListener {
            val intent = Intent(requireContext(), ThemeSearchActivity::class.java)
            startActivity(intent)
        }
    }

    private fun openDetailActivity(beanDetails: KeyboardTheme) {
        val intent = Intent(requireContext(), ThemeDetailActivity::class.java).apply {
            putExtra(ThemeDetailActivity.SOURCE_KEY, beanDetails)
            putExtra(ThemeDetailActivity.DISPLAY_URL_KEY, beanDetails.imgPath)
            putExtra(ThemeDetailActivity.ZIP_URL_KEY, beanDetails.zipPath)
            putExtra(ThemeDetailActivity.NAME_KEY, beanDetails.titleName)
            putExtra(ThemeDetailActivity.GIF_KEY, beanDetails.imgGif)
            val thumbGif = beanDetails.thumbGif
            val thumb = if (thumbGif != null && thumbGif.isNotEmpty()) {
                thumbGif
            } else {
                beanDetails.thumbUrl
            }
            putExtra(ThemeDetailActivity.THUMB_KEY, thumb)
        }
        startActivity(intent)
    }

    override fun onPause() {
        super.onPause()
        stopBannerAutoScroll()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopBannerAutoScroll()
        bannerHandler = null
        bannerRunnable = null
        // 注意：不重置 isDataInitialized，因为 Fragment 视图可能被销毁但 Fragment 实例保留
        // 如果需要在重新创建视图时重新初始化，可以在这里重置标志
    }

    // ViewPager2 水平间距装饰器
    private class HorizontalMarginItemDecoration(
        private val pageMargin: Int,
        private val nextItemVisible: Int
    ) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: android.graphics.Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val position = parent.getChildAdapterPosition(view)
            val itemCount = state.itemCount
            val leftMargin = if (position == 0) 0 else pageMargin / 2
            val rightMargin = if (position == itemCount - 1) 0 else pageMargin / 2
            outRect.set(leftMargin, 0, rightMargin, 0)
        }
    }
}
