'use client'
import { IconButton } from '@/components/ui/button'
import { useMemo, useEffect } from 'react'

interface ChatImagePreviewProps {
  selectedImage: File | null
  imageUploading: boolean
  removeImage: () => void
}

const ChatImagePreview = ({
  selectedImage,
  imageUploading,
  removeImage,
}: ChatImagePreviewProps) => {
  // 使用useMemo缓存ObjectURL，避免每次渲染都创建新的URL
  const imageUrl = useMemo(() => {
    if (!selectedImage) return null
    return URL.createObjectURL(selectedImage)
  }, [selectedImage])

  // 组件卸载或图片变更时清理ObjectURL，避免内存泄漏
  useEffect(() => {
    return () => {
      if (imageUrl) {
        URL.revokeObjectURL(imageUrl)
      }
    }
  }, [imageUrl])

  if (!selectedImage || !imageUrl) {
    return null
  }

  return (
    <div className="ml-4 w-full">
      <div className="relative inline-block">
        <div
          className="relative h-24 w-24 overflow-hidden rounded-lg bg-cover bg-center bg-no-repeat"
          style={{ backgroundImage: `url(${imageUrl})` }}
        >
          {/* 上传进度遮罩 */}
          {imageUploading && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/50">
              <div className="h-6 w-6 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
            </div>
          )}

          {/* 删除按钮 */}
          <div className="absolute top-2 right-2 leading-none">
            <IconButton variant="tertiaryDark" size="mini" onClick={removeImage}>
              <i className="iconfont icon-close" />
            </IconButton>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ChatImagePreview
