import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { Loading } from '@nutui/nutui-react-taro'
import { getBrochurePayload } from './shared'
import './viewer.scss'

function BrochureViewer() {
  const [loading, setLoading] = useState(true)
  const [images, setImages] = useState<string[]>([])
  const [errorMessage, setErrorMessage] = useState('')

  useEffect(() => {
    const loadBrochure = async () => {
      try {
        const { title, images: nextImages } = await getBrochurePayload()
        setImages(nextImages)
        Taro.setNavigationBarTitle({
          title
        })
      } catch (error: any) {
        const nextMessage = error?.message || error?.errMsg || '画册加载失败，请稍后重试'
        setErrorMessage(nextMessage)
        Taro.showToast({
          title: nextMessage,
          icon: 'none'
        })
      } finally {
        setLoading(false)
      }
    }

    loadBrochure()
  }, [])

  if (loading) {
    return (
      <View className="brochure-viewer brochure-viewer--loading">
        <Loading>加载中</Loading>
      </View>
    )
  }

  return (
    <View className="brochure-viewer">
      {errorMessage ? null : images.map((item, index) => (
        <Image
          key={`${item}-${index}`}
          className="brochure-viewer__image"
          src={item}
          mode="widthFix"
          lazyLoad
          showMenuByLongpress
        />
      ))}
    </View>
  )
}

export default BrochureViewer
