package com.erwan.revwatch.ui

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import androidx.viewpager2.widget.ViewPager2
import kotlin.math.abs

/**
 * Wraps a horizontally-scrolling child inside a vertical ViewPager2
 * (or vice-versa) and handles touch-conflict resolution so that the
 * inner scrollable view gets first dibs on events along its own axis.
 */
class NestedScrollableHost @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    private var touchSlop = ViewConfiguration.get(context).scaledTouchSlop
    private var initialX = 0f
    private var initialY = 0f

    private val parentViewPager: ViewPager2?
        get() {
            var v: View? = parent as? View
            while (v != null) {
                if (v is ViewPager2) return v
                v = v.parent as? View
            }
            return null
        }

    private val child: View? get() = if (childCount > 0) getChildAt(0) else null

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        handleInterceptTouchEvent(e)
        return super.onInterceptTouchEvent(e)
    }

    private fun handleInterceptTouchEvent(e: MotionEvent) {
        val parentVP = parentViewPager ?: return
        val orientation = parentVP.orientation

        if (e.action == MotionEvent.ACTION_DOWN) {
            initialX = e.x
            initialY = e.y
            parent.requestDisallowInterceptTouchEvent(true)
        } else if (e.action == MotionEvent.ACTION_MOVE) {
            val dx = e.x - initialX
            val dy = e.y - initialY

            val isVpHorizontal = orientation == ViewPager2.ORIENTATION_HORIZONTAL

            val scaledDx = abs(dx) * if (isVpHorizontal) 0.5f else 1f
            val scaledDy = abs(dy) * if (isVpHorizontal) 1f else 0.5f

            if (scaledDx > touchSlop || scaledDy > touchSlop) {
                if (isVpHorizontal == (scaledDy > scaledDx)) {
                    // Gesture is perpendicular to parent: let parent handle
                    parent.requestDisallowInterceptTouchEvent(false)
                } else {
                    // Gesture is along parent axis
                    val childCanScroll = canChildScroll(if (isVpHorizontal) dx else dy, isVpHorizontal)
                    parent.requestDisallowInterceptTouchEvent(childCanScroll)
                }
            }
        }
    }

    private fun canChildScroll(delta: Float, horizontal: Boolean): Boolean {
        val direction = if (delta > 0) -1 else 1
        val c = child ?: return false
        return if (horizontal) c.canScrollHorizontally(direction) else c.canScrollVertically(direction)
    }
}
