import React, { forwardRef, useCallback, useEffect, useRef, useState } from 'react'
import { useImperativeHandle } from 'react'
import Slider from 'react-slick'
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'
import classNames from 'classnames'
import styles from './index.module.scss' // 自定义样式

type Slide = {
  id: number
  background: string
  content: React.ReactNode
}

type BannerProps = {
  slides: Slide[]
  activeIndex: number
  setActiveIndex: (index: number) => void
}

const VerticalBanner = forwardRef<Slider, BannerProps>(({ slides, activeIndex, setActiveIndex }, ref) => {
  const sliderRef = useRef<Slider>(null)

  // 暴露内部slider实例
  useImperativeHandle(ref, () => sliderRef.current as Slider)

  const isScrolling = useRef(false)


  // 垂直轮播配置
  const settings = {
    vertical: true,
    verticalSwiping: true,
    dots: true,
    dotsClass: 'slick-dots vertical-dots', // 自定义垂直dots样式
    infinite: true,
    speed: 800,
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    autoplay: false,
    adaptiveHeight: true,
    initialSlide: 0,
    beforeChange: (current: number, next: number) => {
      setActiveIndex(next)
      sliderRef.current?.slickGoTo(next)
    }
  }

  // 处理滚轮事件
  const handleWheel = useCallback((e: WheelEvent) => {
    if (isScrolling.current) return

    // 阻止页面默认滚动
    e.preventDefault()

    // 设置滚动锁定，避免连续触发
    isScrolling.current = true
    setTimeout(() => {
      isScrolling.current = false
    }, 1000) // 滚动动画期间锁定

    // 根据滚轮方向切换幻灯片
    if (e.deltaY > 0) {
      sliderRef.current?.slickNext()
      setActiveIndex((activeIndex + 1) % slides.length)
    } else {
      sliderRef.current?.slickPrev()
      setActiveIndex((activeIndex - 1 + slides.length) % slides.length)
    }
    console.log('滚轮事件', slides.length)
  }, [activeIndex, setActiveIndex, slides.length])

  // 注册滚轮事件
  useEffect(() => {
    const handleScroll = (e: WheelEvent) => {
      // 仅在组件挂载时处理
      if (sliderRef.current) {
        handleWheel(e)
      }
    }

    // 添加滚轮事件监听器
    window.addEventListener('wheel', handleScroll, { passive: false })

    return () => {

      window.removeEventListener('wheel', handleScroll)
    }
  }, [handleWheel, setActiveIndex])

  return (
    <div className={styles.banner}>
      <Slider ref={sliderRef} {...settings}>
        {slides.map((slide, index) => {
          const isActive = activeIndex === index
          return (
            <div key={slide.id} className='fullscreen-slide'>
              <div className={classNames('slide-content', { animate: isActive })} style={{ background: `url(${slide.background}) no-repeat center center/cover` }}>
                {slide.content}
              </div>
            </div>
          )
        })}
      </Slider>
    </div>
  )
})

export default VerticalBanner
