import { useState, useCallback, useMemo } from 'react'

interface UseImageViewerOptions {
  /** 初始图片索引 */
  initialIndex?: number
  /** 选择图片后是否自动关闭 */
  autoCloseOnChoose?: boolean
}

export function useImageViewer<T = any>(options: UseImageViewerOptions = {}) {
  const { initialIndex = 0, autoCloseOnChoose = false } = options

  const [isOpen, setIsOpen] = useState(false)
  const [currentIndex, setCurrentIndex] = useState(initialIndex)
  const [images, setImages] = useState<string[]>([])
  // 保存完整的数据快照，用于在查看时保持数据稳定
  const [snapshotData, setSnapshotData] = useState<T[]>([])

  const openViewer = useCallback((imageList: string[], index = 0, dataSnapshot?: T[]) => {
    setImages(imageList)
    setCurrentIndex(index)
    setIsOpen(true)
    // 保存数据快照，防止外部数据更新影响当前查看
    if (dataSnapshot) {
      setSnapshotData([...dataSnapshot]) // 深拷贝快照
    }
  }, [])

  const closeViewer = useCallback(() => {
    setIsOpen(false)
    // 清理快照数据
    setSnapshotData([])
  }, [])

  const handleIndexChange = useCallback((index: number) => {
    setCurrentIndex(index)
  }, [])

  const handleChoose = useCallback(
    (imageUrl: string, index: number) => {
      if (autoCloseOnChoose) {
        setIsOpen(false)
        setSnapshotData([])
      }
      return { imageUrl, index }
    },
    [autoCloseOnChoose]
  )

  // 合并快照数据和实时数据的方法
  const mergeSnapshotWithRealtime = useCallback(
    (
      realtimeData: T[],
      getItemId: (item: T) => string | number,
      mergeStrategy?: (snapshotItem: T, realtimeItem: T) => T
    ): T[] => {
      if (!isOpen || snapshotData.length === 0) {
        return realtimeData
      }

      // 创建实时数据的映射表
      const realtimeMap = new Map<string | number, T>()
      realtimeData.forEach((item) => {
        realtimeMap.set(getItemId(item), item)
      })

      // 合并数据：以快照为基础，但更新可变的状态
      return snapshotData.map((snapshotItem) => {
        const itemId = getItemId(snapshotItem)
        const realtimeItem = realtimeMap.get(itemId)

        if (realtimeItem && mergeStrategy) {
          // 使用自定义合并策略
          return mergeStrategy(snapshotItem, realtimeItem)
        } else if (realtimeItem) {
          // 默认合并策略：保持快照的基础信息，更新状态信息
          return { ...snapshotItem, ...realtimeItem }
        }

        // 如果实时数据中没有对应项，返回快照数据
        return snapshotItem
      })
    },
    [isOpen, snapshotData]
  )

  return {
    // 状态
    isOpen,
    currentIndex,
    images,
    snapshotData,

    // 操作方法
    openViewer,
    closeViewer,
    handleIndexChange,
    handleChoose,
    mergeSnapshotWithRealtime,
  }
}
