'use client'

import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import { cn } from '@/lib/utils'
import { Button, IconButton } from './button'

interface ImageViewerProps {
  /** 图片URL列表 */
  images: string[]
  /** 当前显示的图片索引 */
  currentIndex: number
  /** 是否显示 */
  open: boolean
  /** 关闭回调 */
  onClose: () => void
  /** 索引改变回调 */
  onIndexChange: (index: number) => void
  /** 选择图片回调 */
  onChoose?: (imageUrl: string, index: number) => void
  /** 自定义遮罩层 */
  OverlayComponent?: () => React.ReactNode
  /** 自定义页码渲染 */
  PaginationComponent?: () => React.ReactNode
  /** 自定义操作按钮 */
  ActionComponent?: () => React.ReactNode
  /** 是否显示选择按钮 */
  showChooseButton?: boolean
  /** 是否显示底部控制栏 */
  showBottomBar?: boolean
  /** 是否显示页码 */
  showPagination?: boolean
}

export function ImageViewer({
  images,
  currentIndex,
  open,
  onClose,
  onIndexChange,
  onChoose,
  showChooseButton = true,
  showBottomBar = true,
  showPagination = true,
  OverlayComponent,
  PaginationComponent,
  ActionComponent,
}: ImageViewerProps) {
  const [mounted, setMounted] = useState(false)
  const [loadedMap, setLoadedMap] = useState<Record<number, boolean>>({})

  useEffect(() => {
    setMounted(true)
  }, [])

  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = 'unset'
    }

    return () => {
      document.body.style.overflow = 'unset'
    }
  }, [open])

  // 当外部数据变化导致索引越界时，自动夹取到合法范围
  useEffect(() => {
    if (!open) return
    if (images.length === 0) return
    if (currentIndex < 0 || currentIndex >= images.length) {
      const nextIndex = Math.max(0, Math.min(currentIndex, images.length - 1))
      onIndexChange(nextIndex)
    }
  }, [images.length, currentIndex, open, onIndexChange])

  const handlePrevious = () => {
    if (currentIndex > 0) {
      onIndexChange(currentIndex - 1)
    }
  }

  const handleNext = () => {
    if (currentIndex < images.length - 1) {
      onIndexChange(currentIndex + 1)
    }
  }

  const handleChoose = () => {
    if (onChoose && images[currentIndex]) {
      onChoose(images[currentIndex], currentIndex)
    }
  }

  const renderPagination = () => {
    if (PaginationComponent) {
      return <PaginationComponent />
    }
    return (
      <ImageViewerPaginationContent>
        {currentIndex + 1}/{images.length}
      </ImageViewerPaginationContent>
    )
  }

  if (
    !mounted ||
    !open ||
    images.length === 0 ||
    currentIndex < 0 ||
    currentIndex >= images.length
  ) {
    return null
  }

  return (
    <div className="bg-background-default fixed inset-0 z-50 flex items-center justify-center">
      {OverlayComponent && <OverlayComponent />}
      {/* 关闭按钮 */}
      <IconButton
        iconfont="icon-close"
        onClick={onClose}
        variant="tertiaryDark"
        className="absolute top-6 left-6 z-10"
      />

      {/* 页码显示 */}
      {renderPagination()}

      {/* 主图片 */}
      <div className="relative flex h-full max-h-[100vh] max-h-[1024px] w-full max-w-[765px] items-center justify-center">
        <Image
          src={images[currentIndex]}
          alt={`Image ${currentIndex + 1}`}
          fill
          className="object-contain"
          priority
          onLoadingComplete={() => {
            setLoadedMap((prev) => ({ ...prev, [currentIndex]: true }))
          }}
        />
        {!loadedMap[currentIndex] && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/30">
            <div className="flex flex-col items-center gap-3">
              <div className="size-10 animate-spin rounded-full border-2 border-white/20 border-t-white" />
              <div className="txt-body-m text-white/80">Loading...</div>
            </div>
          </div>
        )}
      </div>

      {/* 底部控制栏 */}
      {showBottomBar && (
        <div className="absolute bottom-12 left-1/2 z-10 flex -translate-x-1/2 transform items-center gap-3 rounded-full bg-[rgba(0,0,0,0.65)] p-2 backdrop-blur backdrop-filter">
          {/* 控制按钮组 */}
          {showPagination && (
            <div className="flex items-center gap-3">
              {/* 左箭头 */}
              <IconButton
                iconfont="icon-arrow-left-border"
                onClick={handlePrevious}
                variant="contrast"
                disabled={currentIndex === 0}
                size="small"
              />

              {/* 右箭头 */}
              <IconButton
                iconfont="icon-arrow-right-border"
                onClick={handleNext}
                variant="contrast"
                disabled={currentIndex === images.length - 1}
                size="small"
              />
            </div>
          )}

          {ActionComponent && <ActionComponent />}

          {/* 分隔线 */}
          {showChooseButton && <div className="bg-outline-normal h-6 w-px" />}

          {/* Choose 按钮 */}
          {showChooseButton && (
            <Button onClick={handleChoose} variant="primary" size="small">
              Choose
            </Button>
          )}
        </div>
      )}
    </div>
  )
}

export function ImageViewerPaginationContent({
  className,
  children,
}: {
  className?: string
  children: React.ReactNode
}) {
  return (
    <div
      className={cn(
        'bg-surface-element-dark-normal txt-numMonotype-s text-txt-primary-specialmap-normal absolute top-12 left-1/2 z-10 flex h-8 min-w-8 -translate-x-1/2 transform items-center justify-center rounded px-2 py-1.5 backdrop-blur',
        className
      )}
    >
      {children}
    </div>
  )
}

// "use client"

// import React, { useEffect, useState } from 'react'
// import { PhotoProvider, PhotoView } from 'react-photo-view'
// import 'react-photo-view/dist/react-photo-view.css'
// import { cn } from '@/lib/utils'
// import { Button, IconButton } from './button'

// interface ImageViewerProps {
//   /** 图片URL列表 */
//   images: string[]
//   /** 当前显示的图片索引 */
//   currentIndex: number
//   /** 是否显示 */
//   open: boolean
//   /** 关闭回调 */
//   onClose: () => void
//   /** 索引改变回调 */
//   onIndexChange: (index: number) => void
//   /** 选择图片回调 */
//   onChoose?: (imageUrl: string, index: number) => void
//   /** 自定义遮罩层 */
//   OverlayComponent?: () => React.ReactNode
//   /** 自定义页码渲染 */
//   PaginationComponent?: () => React.ReactNode
//   /** 自定义操作按钮 */
//   ActionComponent?: () => React.ReactNode
//   /** 是否显示选择按钮 */
//   showChooseButton?: boolean
//   /** 是否显示底部控制栏 */
//   showBottomBar?: boolean
//   /** 是否显示页码 */
//   showPagination?: boolean
// }

// export function ImageViewer({
//   images,
//   currentIndex,
//   open,
//   onClose,
//   onIndexChange,
//   onChoose,
//   showChooseButton = true,
//   showBottomBar = true,
//   showPagination = true,
//   OverlayComponent,
//   PaginationComponent,
//   ActionComponent,
// }: ImageViewerProps) {
//   const [mounted, setMounted] = useState(false)
//   const [currentInternalIndex, setCurrentInternalIndex] = useState(currentIndex)
//   const triggerRefs = React.useRef<(HTMLDivElement | null)[]>([])

//   useEffect(() => {
//     setMounted(true)
//   }, [])

//   // 同步外部索引变化
//   useEffect(() => {
//     setCurrentInternalIndex(currentIndex)
//   }, [currentIndex])

//   // 当外部数据变化导致索引越界时，自动夹取到合法范围
//   useEffect(() => {
//     if (!open) return
//     if (images.length === 0) return
//     if (currentIndex < 0 || currentIndex >= images.length) {
//       const nextIndex = Math.max(0, Math.min(currentIndex, images.length - 1))
//       onIndexChange(nextIndex)
//     }
//   }, [images.length, currentIndex, open, onIndexChange])

//   // 当 open 状态变化时，程序化触发 PhotoView
//   useEffect(() => {
//     if (open && mounted && triggerRefs.current[currentInternalIndex]) {
//       // 延迟触发，确保 DOM 已经渲染
//       const timer = setTimeout(() => {
//         triggerRefs.current[currentInternalIndex]?.click()
//       }, 50)
//       return () => clearTimeout(timer)
//     }
//   }, [open, mounted, currentInternalIndex])

//   const handleChoose = () => {
//     if (onChoose && images[currentInternalIndex]) {
//       onChoose(images[currentInternalIndex], currentInternalIndex)
//     }
//   }

//   const renderPagination = () => {
//     if (PaginationComponent) {
//       return <PaginationComponent />
//     }
//     return <ImageViewerPaginationContent>
//       {currentInternalIndex + 1}/{images.length}
//     </ImageViewerPaginationContent>
//   }

//   const renderOverlay = () => {
//     if (!OverlayComponent) return null
//     return <OverlayComponent />
//   }

//   const renderBottomBar = (photoIndexChange?: (index: number) => void) => {
//     if (!showBottomBar) return null

//     return (
//       <div className="absolute bottom-12 left-1/2 transform -translate-x-1/2 z-10 backdrop-blur backdrop-filter bg-[rgba(0,0,0,0.65)] p-2 rounded-full flex items-center gap-3">
//         {/* 控制按钮组 */}
//         {showPagination && (
//           <div className="flex items-center gap-3">
//             {/* 左箭头 */}
//             <IconButton
//               iconfont="icon-arrow-left-border"
//               onClick={() => {
//                 const newIndex = Math.max(0, currentInternalIndex - 1)
//                 // 使用 react-photo-view 的 onIndexChange 来正确切换图片
//                 if (photoIndexChange) {
//                   photoIndexChange(newIndex)
//                 } else {
//                   // 降级方案：直接更新状态
//                   setCurrentInternalIndex(newIndex)
//                   onIndexChange(newIndex)
//                 }
//               }}
//               variant="contrast"
//               disabled={currentInternalIndex === 0}
//               size="small"
//             />

//             {/* 右箭头 */}
//             <IconButton
//               iconfont="icon-arrow-right-border"
//               onClick={() => {
//                 const newIndex = Math.min(images.length - 1, currentInternalIndex + 1)
//                 // 使用 react-photo-view 的 onIndexChange 来正确切换图片
//                 if (photoIndexChange) {
//                   photoIndexChange(newIndex)
//                 } else {
//                   // 降级方案：直接更新状态
//                   setCurrentInternalIndex(newIndex)
//                   onIndexChange(newIndex)
//                 }
//               }}
//               variant="contrast"
//               disabled={currentInternalIndex === images.length - 1}
//               size="small"
//             />
//           </div>
//         )}

//         {ActionComponent && <ActionComponent />}

//         {/* 分隔线 */}
//         {showChooseButton && (
//           <div className="w-px h-6 bg-outline-normal" />
//         )}

//         {/* Choose 按钮 */}
//         {showChooseButton && (
//           <Button onClick={handleChoose} variant="primary" size="small">
//             Choose
//           </Button>
//         )}
//       </div>
//     )
//   }

//   if (!mounted) {
//     return null
//   }

//   return (
//     <>
//       <PhotoProvider
//         maskOpacity={1}
//         maskClassName="!bg-background-default"
//         onVisibleChange={(visible, index) => {
//           // 当图片查看器关闭时，调用外部的 onClose 回调
//           if (!visible) {
//             onClose()
//           }
//         }}
//         overlayRender={({ index, onIndexChange: photoIndexChange, onClose: photoClose }) => {
//           // 同步 react-photo-view 的索引变化到外部状态
//           if (index !== undefined && index !== currentInternalIndex) {
//             setCurrentInternalIndex(index)
//             onIndexChange(index)
//           }

//           return (
//             <div className="photo-view-toolbar">
//               {/* 关闭按钮 - 使用 react-photo-view 提供的关闭函数 */}
//               <IconButton
//                 iconfont="icon-close"
//                 onClick={() => {
//                   // 使用 react-photo-view 提供的关闭函数
//                   if (photoClose) {
//                     photoClose()
//                   } else {
//                     // 降级方案
//                     onClose()
//                   }
//                 }}
//                 variant="tertiaryDark"
//                 className="absolute top-6 left-6 z-11"
//               />

//               {/* 页码显示 */}
//               {showPagination && renderPagination()}

//               {/* 自定义遮罩层 */}
//               {renderOverlay()}

//               {/* 底部控制栏 - 传递 photoIndexChange 用于箭头导航 */}
//               {renderBottomBar(photoIndexChange)}
//             </div>
//           )
//         }}
//       >
//         {images.map((src, index) => (
//           <PhotoView key={`${src}-${index}`} src={src}>
//             <div
//               ref={(el) => {
//                 triggerRefs.current[index] = el
//               }}
//               style={{
//                 width: 1,
//                 height: 1,
//                 position: 'absolute',
//                 top: -9999,
//                 left: -9999,
//                 opacity: 0,
//                 pointerEvents: 'auto'
//               }}
//             />
//           </PhotoView>
//         ))}
//       </PhotoProvider>
//     </>
//   )
// }

// export function ImageViewerPaginationContent({ className, children }: { className?: string, children: React.ReactNode }) {
//   return (
//     <div className={cn("absolute top-12 left-1/2 transform -translate-x-1/2 z-11 backdrop-blur bg-surface-element-dark-normal px-2 py-1.5 rounded min-w-8 h-8 flex items-center justify-center txt-numMonotype-s text-txt-primary-specialmap-normal", className)}>
//       {children}
//     </div>
//   )
// }
