import { useState } from 'react'
import { Swiper, SwiperItem, Image, View } from '@tarojs/components'
import './index.css'

interface SwiperItemType {
  value: string
  ariaLabel?: string
}

interface SwiperProps {
  images: string[] | SwiperItemType[]
  autoplay?: boolean
  current?: number
  interval?: number
  duration?: number
  loop?: boolean
  indicatorDots?: boolean
  indicatorColor?: string
  indicatorActiveColor?: string
  vertical?: boolean
  previousMargin?: string
  nextMargin?: string
  displayMultipleItems?: number
  height?: string
  onChange?: (current: number) => void
  onTap?: (index: number) => void
}

export default function TDesignSwiper({
  images = [],
  autoplay = true,
  current = 0,
  interval = 5000,
  duration = 300,
  loop = true,
  indicatorDots = true,
  indicatorColor = '#999',
  indicatorActiveColor = '#fa550f',
  vertical = false,
  previousMargin = '0',
  nextMargin = '0',
  displayMultipleItems = 1,
  height = '192rpx',
  onChange,
  onTap
}: SwiperProps) {
  const [currentIndex, setCurrentIndex] = useState(current)

  const handleChange = (e: any) => {
    const newIndex = e.detail.current
    setCurrentIndex(newIndex)
    onChange?.(newIndex)
  }

  const handleTap = (index: number) => {
    onTap?.(index)
  }

  const getImageUrl = (item: string | SwiperItemType): string => {
    return typeof item === 'string' ? item : item.value
  }

  const getAriaLabel = (item: string | SwiperItemType, index: number): string => {
    if (typeof item === 'object' && item.ariaLabel) {
      return item.ariaLabel
    }
    return `轮播图 ${index + 1}`
  }

  return (
    <View className="tdesign-swiper">
      <Swiper
        className="tdesign-swiper__host"
        autoplay={autoplay}
        current={currentIndex}
        interval={interval}
        duration={duration}
        circular={loop}
        vertical={vertical}
        previousMargin={previousMargin}
        nextMargin={nextMargin}
        displayMultipleItems={displayMultipleItems}
        indicatorDots={indicatorDots}
        indicatorColor={indicatorColor}
        indicatorActiveColor={indicatorActiveColor}
        style={{ height }}
        onChange={handleChange}
      >
        {images.map((item: string | SwiperItemType, index: number) => (
          <SwiperItem key={index}>
            <View
              className="tdesign-swiper__item"
              onClick={() => handleTap(index)}
              aria-hidden={currentIndex !== index}
              aria-role="image"
              aria-label={getAriaLabel(item, index)}
            >
              <Image
                src={getImageUrl(item)}
                mode="aspectFill"
                className="tdesign-swiper__image"
                style={{ height }}
              />
            </View>
          </SwiperItem>
        ))}
      </Swiper>
    </View>
  )
}