import { useCallback, useEffect, useRef, useState } from 'react'

interface UseUpwardInfiniteScrollOptions {
  /**
   * 是否有更多数据可以加载
   */
  hasNextPage: boolean
  /**
   * 是否正在加载
   */
  isLoading: boolean
  /**
   * 加载下一页的函数
   */
  fetchNextPage: () => void
  /**
   * 触发加载的阈值(px)，当距离容器顶部多少像素时触发加载
   */
  threshold?: number
  /**
   * 是否启用（默认为true）
   */
  enabled?: boolean
  /**
   * 外部传入的容器ref，如果不传入则使用内部创建的ref
   */
  containerRef?: React.RefObject<HTMLDivElement | null>
}

/**
 * 向上滚动的无限滚动Hook
 * 适用于聊天消息等需要向上加载历史数据的场景
 */
export function useUpwardInfiniteScroll({
  hasNextPage,
  isLoading,
  fetchNextPage,
  threshold = 200,
  enabled = true,
  containerRef: externalContainerRef,
}: UseUpwardInfiniteScrollOptions) {
  const [isFetching, setIsFetching] = useState(false)
  const observerRef = useRef<IntersectionObserver | null>(null)
  const loadMoreRef = useRef<HTMLDivElement>(null)
  const internalContainerRef = useRef<HTMLDivElement>(null)
  const containerRef = externalContainerRef || internalContainerRef
  const [prevScrollHeight, setPrevScrollHeight] = useState(0)

  // 使用ref存储防抖定时器，避免闭包问题
  const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null)
  // 使用ref存储最后加载时间，实现节流
  const lastLoadTimeRef = useRef<number>(0)
  // 使用ref存储最新的loadMore函数，避免Observer重建
  const loadMoreRef2 = useRef<() => void>(undefined)

  // 加载更多数据 - 增强防重复触发机制
  const loadMore = useCallback(async () => {
    const now = Date.now()

    // 多重检查防止重复请求
    if (!hasNextPage || isLoading || isFetching) return

    // 节流：距离上次加载至少800毫秒
    if (now - lastLoadTimeRef.current < 800) {
      if (process.env.NODE_ENV === 'development') {
        console.log('🚫 加载被节流限制，距离上次加载不足800ms')
      }
      return
    }

    lastLoadTimeRef.current = now

    // 记录加载前的滚动高度
    if (containerRef.current) {
      setPrevScrollHeight(containerRef.current.scrollHeight)
    }

    setIsFetching(true)

    if (process.env.NODE_ENV === 'development') {
      console.log('🔄 开始加载更多数据')
    }

    try {
      fetchNextPage()
    } finally {
      // 延迟重置状态，确保DOM更新完成
      setTimeout(() => {
        setIsFetching(false)
        if (process.env.NODE_ENV === 'development') {
          console.log('✅ 加载更多完成，重置fetching状态')
        }
      }, 600) // 优化到600ms，平衡性能和稳定性
    }
  }, [hasNextPage, isLoading, isFetching, fetchNextPage])

  // 更新loadMore ref
  useEffect(() => {
    loadMoreRef2.current = loadMore
  })

  // 保持滚动位置 - 在新内容加载后调整滚动位置
  useEffect(() => {
    if (!containerRef.current || prevScrollHeight === 0) return

    const container = containerRef.current
    const newScrollHeight = container.scrollHeight
    const scrollHeightDiff = newScrollHeight - prevScrollHeight

    // 调整滚动位置以保持用户当前查看的内容不变
    if (scrollHeightDiff > 0) {
      const newScrollTop = container.scrollTop + scrollHeightDiff
      container.scrollTop = newScrollTop

      if (process.env.NODE_ENV === 'development') {
        console.log('📐 调整滚动位置:', {
          prevScrollHeight,
          newScrollHeight,
          scrollHeightDiff,
          oldScrollTop: container.scrollTop - scrollHeightDiff,
          newScrollTop,
        })
      }
    }

    setPrevScrollHeight(0)
  }, [prevScrollHeight])

  // 设置Intersection Observer
  useEffect(() => {
    if (!enabled || !loadMoreRef.current || !containerRef.current) {
      if (process.env.NODE_ENV === 'development') {
        console.log('🔍 IntersectionObserver 未启用:', {
          enabled,
          hasLoadMoreRef: !!loadMoreRef.current,
          hasContainerRef: !!containerRef.current,
          containerElement: containerRef.current,
        })
      }
      return
    }

    const options = {
      root: containerRef.current,
      rootMargin: `${threshold}px 0px 0px 0px`,
      threshold: 0.1,
    }

    if (process.env.NODE_ENV === 'development') {
      console.log('🔍 设置 IntersectionObserver:', {
        root: containerRef.current,
        rootMargin: options.rootMargin,
        threshold: options.threshold,
      })
    }

    observerRef.current = new IntersectionObserver((entries) => {
      const [entry] = entries
      if (process.env.NODE_ENV === 'development') {
        console.log('🔍 IntersectionObserver 回调:', {
          isIntersecting: entry.isIntersecting,
          intersectionRatio: entry.intersectionRatio,
          boundingClientRect: entry.boundingClientRect,
          rootBounds: entry.rootBounds,
        })
      }

      if (entry.isIntersecting) {
        // 清除之前的防抖定时器
        if (debounceTimeoutRef.current) {
          clearTimeout(debounceTimeoutRef.current)
        }

        // 防抖：延迟执行加载，避免快速滚动时多次触发
        debounceTimeoutRef.current = setTimeout(() => {
          if (loadMoreRef2.current) {
            if (process.env.NODE_ENV === 'development') {
              console.log('🔍 触发加载更多 (通过 IntersectionObserver)')
            }
            loadMoreRef2.current()
          }
        }, 200) // 优化防抖延迟为200ms，提升响应速度
      } else {
        // 当元素不再可见时，清除防抖定时器
        if (debounceTimeoutRef.current) {
          clearTimeout(debounceTimeoutRef.current)
          debounceTimeoutRef.current = null
        }
      }
    }, options)

    const currentRef = loadMoreRef.current
    if (currentRef) {
      observerRef.current.observe(currentRef)

      if (process.env.NODE_ENV === 'development') {
        console.log('🔍 开始观察加载触发器元素:', currentRef)
      }
    }

    return () => {
      if (observerRef.current && currentRef) {
        observerRef.current.unobserve(currentRef)
      }
      // 清理防抖定时器
      if (debounceTimeoutRef.current) {
        clearTimeout(debounceTimeoutRef.current)
        debounceTimeoutRef.current = null
      }
    }
  }, [enabled, threshold]) // 移除loadMore依赖，避免Observer频繁重建

  // 清理observer
  useEffect(() => {
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect()
      }
    }
  }, [])

  return {
    loadMoreRef,
    containerRef: externalContainerRef ? undefined : containerRef, // 如果外部传入了containerRef，就不返回内部的
    isFetching,
    loadMore,
  }
}
