package com.design.zenspace.preview

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.design.zenspace.tools.CenterSnapHelper
import com.design.zenspace.DApplication
import com.design.zenspace.tools.TagAdapter
import com.design.zenspace.tools.TagItem
import com.design.zenspace.entity.Feature
import com.design.zenspace.entity.MainViewModel
import com.design.zenspace.databinding.FragmentTagShowBinding
import com.design.zenspace.tools.MoreAndSearchAdapter
import com.design.zenspace.tools.SecFavListener
import kotlin.math.abs


class TagShowFragment : Fragment(),SecFavListener {
    private lateinit var binding: FragmentTagShowBinding
    private lateinit var viewModel:MainViewModel
    private lateinit var tagAdapter: TagAdapter
    private val snapHelper = CenterSnapHelper()
    private var isScrolling = false
    private var pendingScrollPosition = -1
    private lateinit var adapter:MoreAndSearchAdapter
    private val tagList = mutableListOf<TagItem>()
    private var currentTagName = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding=FragmentTagShowBinding.inflate(inflater,container,false)
        val classificationList = DApplication.classificationList
        viewModel=ViewModelProvider(this)[MainViewModel::class.java]
        for(index in 0 until classificationList.size){
            tagList.add(TagItem(index , classificationList[index]))
        }
        initRecyclerView() // 先初始化 Adapter
        setupRecyclerView()
        setupDataObserver() // 设置数据观察
        return binding.root
    }

    private fun setupRecyclerView() {
        // 设置布局管理器
        val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        binding.rvTags.layoutManager = layoutManager

        // 创建适配器
        tagAdapter = TagAdapter(tagList) { selectedTag, position ->
            Log.d("ClassificationFragment00", "Selected tag: ${selectedTag.name}")
            updateSelectedText(selectedTag.name)
            smoothScrollToCenter(position)
        }

        binding.rvTags.adapter = tagAdapter

        // 添加 SnapHelper 实现居中吸附
        snapHelper.attachToRecyclerView(binding.rvTags)

        // 添加滚动状态监听
        binding.rvTags.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                isScrolling = newState != RecyclerView.SCROLL_STATE_IDLE

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 滚动停止时更新选中状态
                    updateSelectedItemFromScroll()

                    // 执行延迟的滚动
                    if (pendingScrollPosition != -1) {
                        val position = pendingScrollPosition
                        pendingScrollPosition = -1
                        executeSmoothScroll(position)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 只在滚动时实时更新（可选，如果不需要实时更新可以去掉）
                // updateSelectedItemFromScroll()
            }
        })

        // 初始选中第一个
//        updateSelectedText(tagList[0].name)

        // 延迟滚动到第一个位置
        binding.rvTags.post {
            smoothScrollToCenter(0)
        }
    }

    private fun smoothScrollToCenter(position: Int) {
        if (isScrolling) {
            // 如果正在滚动，延迟执行
            pendingScrollPosition = position
            return
        }

        executeSmoothScroll(position)
    }

    private fun executeSmoothScroll(position: Int) {
        if (!binding.rvTags.isComputingLayout && !isScrolling) {
            binding.rvTags.smoothScrollToPosition(position)

            // 添加一个小的延迟来确保精确居中
            binding.rvTags.postDelayed({
                if (!binding.rvTags.isComputingLayout) {
                    adjustToExactCenter(position)
                }
            }, 100)
        } else {
            // 如果仍然在计算布局，再次延迟
            pendingScrollPosition = position
        }
    }

    private fun adjustToExactCenter(position: Int) {
        val layoutManager = binding.rvTags.layoutManager as? LinearLayoutManager ?: return

        if (binding.rvTags.isComputingLayout || isScrolling) {
            return
        }

        val targetView = layoutManager.findViewByPosition(position)
        targetView?.let {
            val centerX = it.left + it.width / 2
            val targetScrollX = centerX - binding.rvTags.width / 2

            // 只在需要调整时才滚动
            if (Math.abs(targetScrollX) > 10) {
                binding.rvTags.smoothScrollBy(targetScrollX, 0)
            }
        }
    }

    private fun updateSelectedItemFromScroll() {
        if (binding.rvTags.isComputingLayout) {
            return
        }

        val layoutManager = binding.rvTags.layoutManager as? LinearLayoutManager ?: return
        val centerX = binding.rvTags.width / 2

        var minDistance = Int.MAX_VALUE
        var centerPosition = 0

        // 找到最接近中心的item
        for (i in 0 until layoutManager.childCount) {
            val child = layoutManager.getChildAt(i) ?: continue
            val position = layoutManager.getPosition(child)
            if (position == RecyclerView.NO_POSITION) continue

            val childCenterX = (child.left + child.right) / 2
            val distance = abs(childCenterX - centerX)

            if (distance < minDistance) {
                minDistance = distance
                centerPosition = position
            }
        }

        // 安全地更新选中状态
        if (centerPosition >= 0 && centerPosition < tagList.size) {
            val currentSelected = tagAdapter.getSelectedPosition()
            if (currentSelected != centerPosition) {
                tagAdapter.notifyItemChanged(currentSelected)
                tagAdapter.notifyItemChanged(centerPosition)
                Log.d("ClassificationFragment", "Selected tag: ${currentSelected}")
                updateSelectedText(tagList[currentSelected].name)
            }
        }
    }
    private fun setupDataObserver() {
        // 统一设置数据观察者
        viewModel.classificationList.observe(viewLifecycleOwner) { list ->
            if (list.isNotEmpty() && currentTagName == viewModel.currentTitleName) {
                updateUI(list)
            } else if (list.isEmpty()) {
                // 处理空数据情况
                binding.searchPb.visibility = View.GONE
                adapter.setList(emptyList())
                adapter.notifyDataSetChanged()
            }
        }
    }

    private fun initRecyclerView() {
        adapter = MoreAndSearchAdapter()
        adapter.setListener(this)
        binding.list.layoutManager = GridLayoutManager(requireContext(), 2)
        binding.list.adapter = adapter
    }

    private fun updateSelectedText(tagName: String) {
        Log.d("ClassificationFragment", "updateSelectedText: $tagName")

        // 如果点击的是当前已选中的标签，不重复请求
        if (currentTagName == tagName) {
            Log.d("ClassificationFragment", "Same tag selected, skip request")
            return
        }

        currentTagName = tagName
        viewModel.currentTitleName = tagName

        // 显示加载状态
        binding.searchPb.visibility = View.VISIBLE

        // 先清空旧数据，显示加载状态
        adapter.setList(emptyList())
        adapter.notifyDataSetChanged()

        // 强制重新获取数据
        Log.d("ClassificationFragment", "Requesting data for: $tagName")
        viewModel.getClassificationList(tagName)
    }

    private fun updateUI(list: List<Feature>) {
        Log.d("ClassificationFragment", "updateUI: ${list.size} items for $currentTagName")

        // 确保当前显示的数据与当前选中的标签匹配
        if (currentTagName == viewModel.currentTitleName) {
            adapter.setList(list)
            binding.searchPb.visibility = View.GONE
            adapter.notifyDataSetChanged()
            Log.d("ClassificationFragment", "UI updated successfully")
        } else {
            Log.d("ClassificationFragment", "Data mismatch, current: $currentTagName, data for: ${viewModel.currentTitleName}")
        }
    }

    override fun inItemClick(feature: Feature) {
        val intent= Intent(requireActivity(),PreviewBigActivity::class.java)
        intent.putExtra(PreviewBigActivity.paperKey,feature)
        startActivity(intent)
    }
}