package com.example.myapplication.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.myapplication.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.card.MaterialCardView
import android.graphics.drawable.TransitionDrawable
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.HorizontalScrollView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import kotlin.math.abs
import android.content.Intent
import com.example.myapplication.ImeGuideActivity

class HomeFragment : Fragment() {

    private lateinit var bottomSheet: MaterialCardView
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<MaterialCardView>
    private lateinit var scrim: View
    private lateinit var viewPager: ViewPager2
    private lateinit var tagContainer: LinearLayout
    private lateinit var tagScroll: HorizontalScrollView
    private lateinit var header: View
    private lateinit var tabList1: TextView
    private lateinit var tabList2: TextView
    private lateinit var backgroundImage: ImageView
    private var parentWidth = 0
    private var parentHeight = 0

    private val dragToCloseThreshold by lazy {
        val dp = 40f
        (dp * resources.displayMetrics.density)
    }

    // 第二个列表的“标签页”，数量不固定，可以从服务端/本地配置来
    private val tags = listOf("标签一", "标签二", "标签三", "标签四", "标签五", "标签六", "标签七", "标签八", "标签九", "标签十")

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 充值按钮点击
        view.findViewById<View>(R.id.rechargeButton).setOnClickListener {
            findNavController().navigate(R.id.action_global_rechargeFragment)
        }
        //输入法激活跳转
        view.findViewById<ImageView>(R.id.floatingImage).setOnClickListener {
            startActivity(Intent(requireContext(), ImeGuideActivity::class.java))
        }

        scrim = view.findViewById(R.id.view_scrim)
        bottomSheet = view.findViewById(R.id.bottomSheet)
        tagContainer = view.findViewById(R.id.tagContainer)
        tagScroll = view.findViewById(R.id.tagScroll)
        header = view.findViewById(R.id.bottomSheetHeader)
        tabList1 = view.findViewById(R.id.tab_list1)
        tabList2 = view.findViewById(R.id.tab_list2)
        viewPager = view.findViewById(R.id.viewPager)
        backgroundImage = bottomSheet.findViewById(R.id.backgroundImage)
        val root = view.findViewById<CoordinatorLayout>(R.id.rootCoordinator)
        val floatingImage = view.findViewById<ImageView>(R.id.floatingImage)
        // 拿到父布局的宽高（需要等布局完成）
        root.post {
            parentWidth = root.width
            parentHeight = root.height
        }

        initDrag(floatingImage, root)
        setupBottomSheet(view)
        setupViewPager()
        setupTopTabs()
        setupTags()
    }
    // ---------------- 拖拽效果 ----------------
    private fun initDrag(target: View, parent: ViewGroup) {
        var dX = 0f
        var dY = 0f
        var lastRawX = 0f
        var lastRawY = 0f
        var isDragging = false
    
        val touchSlop = ViewConfiguration.get(requireContext()).scaledTouchSlop
    
        target.setOnTouchListener { v, event ->
            when (event.actionMasked) {
    
                MotionEvent.ACTION_DOWN -> {
                    // 告诉 CoordinatorLayout：别拦截这次事件
                    parent.requestDisallowInterceptTouchEvent(true)
                    // 暂时禁止 BottomSheet 拖动
                    if (::bottomSheetBehavior.isInitialized) {
                        bottomSheetBehavior.isDraggable = false
                    }
    
                    dX = v.x - event.rawX
                    dY = v.y - event.rawY
                    lastRawX = event.rawX
                    lastRawY = event.rawY
                    isDragging = false
                    true
                }
    
                MotionEvent.ACTION_MOVE -> {
                    val dxMove = event.rawX - lastRawX
                    val dyMove = event.rawY - lastRawY
                    if (!isDragging && (abs(dxMove) > touchSlop || abs(dyMove) > touchSlop)) {
                        isDragging = true
                    }
    
                    if (isDragging) {
                        var newX = event.rawX + dX
                        var newY = event.rawY + dY
    
                        // 限制在父布局范围内
                        val maxX = parentWidth - v.width
                        val maxY = parentHeight - v.height
    
                        newX = newX.coerceIn(0f, maxX.toFloat())
                        newY = newY.coerceIn(0f, maxY.toFloat())
    
                        v.x = newX
                        v.y = newY
                    }
    
                    lastRawX = event.rawX
                    lastRawY = event.rawY
                    true
                }
    
                MotionEvent.ACTION_UP,
                MotionEvent.ACTION_CANCEL -> {
                    // 允许父布局继续拦截之后的事件
                    parent.requestDisallowInterceptTouchEvent(false)
                    // 恢复 BottomSheet 可拖动
                    if (::bottomSheetBehavior.isInitialized) {
                        bottomSheetBehavior.isDraggable = true
                    }
    
                    if (!isDragging) {
                        v.performClick()
                    }
    
                    // 手指抬起：吸边
                    snapToEdge(v)
                    true
                }
    
                else -> false
            }
        }
    }
    

    /**
     * 吸边逻辑：左右贴边（需要上下也吸边可以再扩展）
     */
    private fun snapToEdge(v: View) {
        if (parentWidth == 0 || parentHeight == 0) return

        val centerX = v.x + v.width / 2f
        val toLeft = centerX < parentWidth / 2f

        val targetX = if (toLeft) 0f else (parentWidth - v.width).toFloat()

        // 如果你还想限制上下边距，比如离底部留 80dp 不遮挡 BottomSheet，可以再处理 y
        val minTop = 0f
        val maxBottom = (parentHeight - v.height).toFloat()
        val targetY = v.y.coerceIn(minTop, maxBottom)

        v.animate()
            .x(targetX)
            .y(targetY)
            .setDuration(200)
            .start()
    }
    // ---------------- BottomSheet 行为 ----------------

    private fun setupBottomSheet(root: View) {
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)

        // 允许拖拽，允许嵌套滚动控制
        bottomSheetBehavior.isDraggable = true
        bottomSheetBehavior.isHideable = false
        bottomSheetBehavior.isFitToContents = false
        // 展开时高度占屏幕 70%
        bottomSheetBehavior.halfExpandedRatio = 0.7f

        // 先等布局完成之后，计算“按钮下面剩余空间”作为 peekHeight
        root.post {
            val coordinatorHeight = root.height-40
            val button = root.findViewById<View>(R.id.rechargeButton)
            val buttonBottom = button.bottom
            val peek = (coordinatorHeight - buttonBottom).coerceAtLeast(200)
            bottomSheetBehavior.peekHeight = peek
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }

        // 监听状态变化，用来控制遮罩显示/隐藏
        bottomSheetBehavior.addBottomSheetCallback(object :
            BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_COLLAPSED -> {
                        scrim.isVisible = false
                    }
                    BottomSheetBehavior.STATE_DRAGGING,
                    BottomSheetBehavior.STATE_EXPANDED,
                    BottomSheetBehavior.STATE_HALF_EXPANDED -> {
                        scrim.isVisible = true
                    }
                    else -> {}
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                // 跟随滑动渐变遮罩透明度
                if (slideOffset >= 0f) {
                    scrim.alpha = slideOffset.coerceIn(0f, 1f)
                }
            }
        })

        // 点击遮罩，关闭回原位
        scrim.setOnClickListener {
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }

        // 简单的“空白区域下滑”关闭：在遮罩上响应手势（简单版，只要 move 就关）
        scrim.setOnTouchListener { _, event ->
            // 这里可以更精细地判断手势方向，这里简单处理为：有滑动就关闭
            // 如果你想更准，可以根据 down / move 的 dy 判断
            // 为了示例就写得简单一点
            // MotionEvent.ACTION_MOVE = 2
            if (event.action == 2) {
                bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                true
            } else {
                false
            }
        }

        // 点击底部盒子的“头部”，在折叠 / 半展开之间切换
        header.setOnClickListener {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED -> {
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
                }
                BottomSheetBehavior.STATE_HALF_EXPANDED,
                BottomSheetBehavior.STATE_EXPANDED -> {
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                }
                else -> {}
            }
        }
    }

    // ---------------- ViewPager2 + 列表 ----------------

    private fun setupViewPager() {
        val pageCount = 1 + tags.size // 1 = 第一个列表，剩下的是第二个列表的标签页
        viewPager.adapter = SheetPagerAdapter(pageCount)
    
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateTabsAndTags(position) // 里面会调用 highlightTag，把标签高亮并滚动
            }
        })
    }

    // 顶部“列表一 / 列表二”选项栏点击
    private fun setupTopTabs() {
        tabList1.setOnClickListener {
            viewPager.currentItem = 0   // 列表一
        }
        tabList2.setOnClickListener {
            viewPager.currentItem = 1   // 列表二的第一个标签页
        }
    }

    // 顶部标签行（只在第二个列表时可见）
    private fun setupTags() {
        tagContainer.removeAllViews()
        tags.forEachIndexed { index, tag ->
            val tv = layoutInflater.inflate(
                R.layout.item_tag,
                tagContainer,
                false
            ) as TextView
            tv.text = tag
            tv.setOnClickListener {
                // 当前位置 = 1 + 标签下标
                viewPager.currentItem = 1 + index
            }
            tagContainer.addView(tv)
        }
        // 默认选中列表一，所以标签行默认隐藏
        tagScroll.isVisible = false
    }

    // 根据当前 page 更新上方两个选项 & 标签高亮/显隐
    private fun updateTabsAndTags(position: Int) {

        if (position == 0) {
            tabList1.setTextColor(requireContext().getColor(R.color.black))
            tabList2.setTextColor(requireContext().getColor(R.color.light_black))
            tagScroll.isVisible = false
            
            fadeImage(backgroundImage, R.drawable.option_background)
    
        } else {
    
            tabList1.setTextColor(requireContext().getColor(R.color.light_black))
            tabList2.setTextColor(requireContext().getColor(R.color.black))
            tagScroll.isVisible = true
            
            fadeImage(backgroundImage, R.drawable.option_background_two)
    
            val tagIndex = position - 1
            highlightTag(tagIndex)
        }
    }
    //背景淡入淡出
    private fun fadeImage(imageView: ImageView, newImageRes: Int) {
        val oldDrawable = imageView.drawable
        val newDrawable = ContextCompat.getDrawable(requireContext(), newImageRes)
    
        if (newDrawable == null) {
            return
        }
    
        // 第一次还没有旧图，直接设置就好
        if (oldDrawable == null) {
            imageView.setImageDrawable(newDrawable)
            return
        }
    
        val transitionDrawable = TransitionDrawable(arrayOf(oldDrawable, newDrawable)).apply {
            // 关键：启用交叉淡入淡出，旧图才会一起淡出
            isCrossFadeEnabled = true
        }
    
        imageView.setImageDrawable(transitionDrawable)
        transitionDrawable.startTransition(300) // 300ms 淡入淡出
    }
    

    private fun highlightTag(index: Int) {
        for (i in 0 until tagContainer.childCount) {
            val child = tagContainer.getChildAt(i) as TextView
            if (i == index) {
                child.setBackgroundResource(R.drawable.tag_selected_bg)
                child.setTextColor(requireContext().getColor(android.R.color.white))
    
                // 关键：把选中的标签滚动到可见（这里我用“居中”效果）
                tagScroll.post {
                    val scrollViewWidth = tagScroll.width
                    val childCenter = child.left + child.width / 2
                    val targetScrollX = childCenter - scrollViewWidth / 2
                    tagScroll.smoothScrollTo(targetScrollX.coerceAtLeast(0), 0)
                }
    
            } else {
                child.setBackgroundResource(R.drawable.tag_unselected_bg)
                child.setTextColor(requireContext().getColor(R.color.light_black))
            }
        }
    }
    

    // ---------------- 共享的 ViewHolder 类 ----------------
    
    inner class PageViewHolder(val recyclerView: RecyclerView) :
        RecyclerView.ViewHolder(recyclerView)

    // ---------------- ViewPager2 的 Adapter ----------------

    /**
     * 每一页都是一个 RecyclerView 卡片列表：
     *  - position = 0：列表一（数据 A）
     *  - position >= 1：列表二的第 index 个标签页（数据 B[index]）
     */
    inner class SheetPagerAdapter(
        private val pageCount: Int
    ) : RecyclerView.Adapter<SheetPagerAdapter.PageViewHolder>() {
    
        inner class PageViewHolder(val root: View) : RecyclerView.ViewHolder(root)
    
        override fun getItemViewType(position: Int): Int {
            // 0：第一个列表页，>0：第二个列表的各标签页
            return if (position == 0) 0 else 1
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
            val layoutId = when (viewType) {
                0 -> R.layout.bottom_page_list1   // 第一个列表的自定义内容
                else -> R.layout.bottom_page_list2 // 第二个列表各标签页的自定义内容
            }
    
            val root = LayoutInflater.from(parent.context)
                .inflate(layoutId, parent, false)
    
            // 如果需要，禁用嵌套滚动（对 NestedScrollView 一般问题不大，可以不写）
            // root.findViewById<NestedScrollView>(R.id.scrollContent)?.isNestedScrollingEnabled = false
    
            return PageViewHolder(root)
        }
    
        override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
            val root = holder.root
    
            if (position == 0) {
                // 这里可以拿到 bottom_page_list1 中的控件，做一些初始化
                // val someView = root.findViewById<TextView>(R.id.xxx)
                // someView.text = "xxx"
    
            } else {
                // // 第二个列表对应的标签页
                // val tagIndex = position - 1
                // val tagName = tags[tagIndex]
    
                // // 示例：把标题改成“标签一的内容 / 标签二的内容 ……”
                // val titleView = root.findViewById<TextView>(R.id.pageTitle)
                // titleView?.text = "$tagName 的自定义内容"
    
                // // 你也可以根据 tagIndex，显示/隐藏不同区域
            }
    
            //让当前页里的滚动容器具备“下拉关闭 BottomSheet”的能力
            val scrollContent = root.findViewById<View>(R.id.scrollContent)
            if (scrollContent != null) {
                setupPullToClose(scrollContent)
            }
        }
    
        override fun getItemCount(): Int = pageCount
    }
    
    


    private fun setupPullToClose(scrollable: View) {
        var downY = 0f
        var isDraggingToClose = false
    
        scrollable.setOnTouchListener { _, event ->
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    downY = event.rawY
                    isDraggingToClose = false
                }
    
                MotionEvent.ACTION_MOVE -> {
                    // 已经是折叠状态，不拦截，交给内容自己滚（其实也滚不动多少）
                    if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED) {
                        return@setOnTouchListener false
                    }
    
                    val dy = event.rawY - downY
    
                    if (!scrollable.canScrollVertically(-1) &&      // 已在顶部
                        dy > dragToCloseThreshold &&                 // 向下拉超过阈值
                        (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED ||
                                bottomSheetBehavior.state == BottomSheetBehavior.STATE_HALF_EXPANDED)
                    ) {
                        isDraggingToClose = true
                        bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                        return@setOnTouchListener true
                    }
                }
    
                MotionEvent.ACTION_UP,
                MotionEvent.ACTION_CANCEL -> {
                    isDraggingToClose = false
                }
            }
    
            isDraggingToClose
        }
    }
    
}
