'use client'

import { useState, useEffect, useRef, useCallback } from 'react'
import { IconButton } from '@/components/ui/button'
import { useGetMemberDetail } from '@/hooks/useWallet'
import { VipType } from '@/services/wallet'

const AUTO_PLAY_INTERVAL = 4000 // 自动轮播间隔 4 秒

const FADE_DURATION = 400 // 渐变动画时长（毫秒）

const CarouselBanner = ({ vipType, visible }: { vipType?: VipType; visible: boolean }) => {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isPaused, setIsPaused] = useState(false) // 鼠标悬停时暂停轮播
  const [isFading, setIsFading] = useState(false) // 控制淡入淡出动画
  const { data: memberDetail, isLoading } = useGetMemberDetail()
  const { memberPrivList } = memberDetail || {}
  const autoPlayTimerRef = useRef<NodeJS.Timeout | null>(null)
  const pendingIndexRef = useRef<number | null>(null)

  // 将 memberPrivList 转换为轮播数据格式
  const carouselData =
    memberPrivList?.map((item, index) => ({
      id: item.id || index,
      title: item.title || 'VIP Feature',
      description: item.desc || 'Enjoy exclusive VIP benefits',
      backgroundImage: item.img || '/images/vip/drawer-bg.png',
    })) || []

  // 清除定时器
  const clearAutoPlayTimer = useCallback(() => {
    if (autoPlayTimerRef.current) {
      clearInterval(autoPlayTimerRef.current)
      autoPlayTimerRef.current = null
    }
  }, [])

  // 启动自动轮播定时器
  const startAutoPlayTimer = useCallback(() => {
    clearAutoPlayTimer()
    if (visible && carouselData.length > 1 && !isPaused) {
      autoPlayTimerRef.current = setInterval(() => {
        setCurrentIndex((prev) => (prev + 1) % carouselData.length)
      }, AUTO_PLAY_INTERVAL)
    }
  }, [visible, carouselData.length, isPaused, clearAutoPlayTimer])

  // 鼠标悬停时暂停轮播
  const handleMouseEnter = () => {
    setIsPaused(true)
    clearAutoPlayTimer()
  }

  // 鼠标离开时恢复轮播
  const handleMouseLeave = () => {
    setIsPaused(false)
  }

  // 带渐变动画的切换
  const changeSlideWithFade = useCallback(
    (newIndex: number) => {
      if (isFading) return // 防止动画过程中重复触发
      setIsFading(true)
      pendingIndexRef.current = newIndex
      setTimeout(() => {
        setCurrentIndex(newIndex)
        setIsFading(false)
      }, FADE_DURATION)
    },
    [isFading]
  )

  const nextSlide = () => {
    if (carouselData.length > 0 && !isFading) {
      const newIndex = (currentIndex + 1) % carouselData.length
      changeSlideWithFade(newIndex)
      startAutoPlayTimer() // 手动切换后重置定时器
    }
  }

  const prevSlide = () => {
    if (carouselData.length > 0 && !isFading) {
      const newIndex = (currentIndex - 1 + carouselData.length) % carouselData.length
      changeSlideWithFade(newIndex)
      startAutoPlayTimer() // 手动切换后重置定时器
    }
  }

  // 自动轮播（带渐变动画）
  useEffect(() => {
    if (visible && carouselData.length > 1 && !isPaused) {
      autoPlayTimerRef.current = setInterval(() => {
        setIsFading(true)
        setTimeout(() => {
          setCurrentIndex((prev) => (prev + 1) % carouselData.length)
          setIsFading(false)
        }, FADE_DURATION)
      }, AUTO_PLAY_INTERVAL)
    }

    return () => {
      clearAutoPlayTimer()
    }
  }, [visible, carouselData.length, isPaused, clearAutoPlayTimer])

  useEffect(() => {
    if (!memberPrivList) {
      return
    }
    if (visible) {
      if (vipType) {
        const targetIndex = memberPrivList?.findIndex((item) => item.code === vipType) ?? -1
        if (targetIndex >= 0) {
          setCurrentIndex(targetIndex)
        } else {
          setCurrentIndex(0)
        }
      }
    }
  }, [visible, memberPrivList])

  const currentSlide = carouselData[currentIndex]

  // 加载状态
  if (isLoading) {
    return (
      <div className="relative flex w-full flex-col content-stretch items-start justify-start gap-4 px-6">
        {/* 轮播图片容器 - 骨架屏 */}
        <div className="relative flex h-[234px] w-full shrink-0 flex-col content-stretch items-start justify-start gap-1 rounded-[16px] backdrop-blur-md backdrop-filter">
          <div className="relative h-[235px] w-full shrink-0 animate-pulse rounded-[16px] bg-[#2a2a2a]" />
        </div>

        {/* 轮播内容信息 - 骨架屏 */}
        <div className="relative flex w-full shrink-0 flex-col content-stretch items-center justify-start gap-2">
          <div className="h-6 w-1/2 animate-pulse rounded bg-[#2a2a2a]" />
          <div className="h-4 w-3/4 animate-pulse rounded bg-[#2a2a2a]" />
        </div>
      </div>
    )
  }

  return (
    <div
      className="relative flex w-full flex-col content-stretch items-start justify-start gap-4 px-6"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      {/* 轮播图片容器 */}
      <div className="relative flex h-[234px] w-full shrink-0 flex-col content-stretch items-start justify-start gap-1 rounded-[16px]">
        {/* 背景图片 */}
        <div className="relative h-[235px] w-full shrink-0 overflow-hidden rounded-lg bg-cover bg-center bg-no-repeat backdrop-blur-[12px] transition-all duration-500 ease-in-out">
          <div className="bg-background-district absolute inset-0 transition-all duration-500 ease-in-out" />
          <div
            className={`relative h-full w-full transition-opacity duration-300 ease-in-out ${isFading ? 'opacity-0' : 'opacity-100'}`}
          >
            <img src={currentSlide.backgroundImage} className="h-full w-full object-cover" />
          </div>
        </div>

        {/* 右箭头按钮 - 只有多个项目时才显示 */}
        {carouselData.length > 1 && (
          <div className="absolute top-1/2 -right-4 translate-y-[-50%]">
            <IconButton
              iconfont="icon-arrow-right-border"
              variant="tertiaryDark"
              size="small"
              onClick={nextSlide}
            />
          </div>
        )}

        {/* 左箭头按钮 - 只有多个项目时才显示 */}
        {carouselData.length > 1 && (
          <div className="absolute top-1/2 -left-4 z-10 translate-y-[-50%]">
            <IconButton
              iconfont="icon-arrow-left-border"
              variant="tertiaryDark"
              size="small"
              onClick={prevSlide}
            />
          </div>
        )}
      </div>

      {/* 轮播内容信息 */}
      <div className="relative flex w-full shrink-0 flex-col content-stretch items-center justify-start gap-2">
        <div className="relative flex w-full shrink-0 content-stretch items-start justify-center gap-1">
          <div className="txt-title-m relative shrink-0 overflow-hidden overflow-ellipsis">
            {currentSlide.title}
          </div>
        </div>
        <div className="txt-body-m text-txt-secondary-normal relative w-full shrink-0 text-center">
          {currentSlide.description}
        </div>
      </div>
    </div>
  )
}

export default CarouselBanner
