'use client'
import Link from 'next/link'

export const ThumbnailCell = (props: any) => {
  // 尝试从不同的 props 路径获取值
  const value = props.value || props.cellData || props.data
  const rowData = props.rowData || props.row

  // 获取起始价格（已经是美元）
  const startPrice = rowData?.startPrice
  const formattedPrice = startPrice ? `$${startPrice.toFixed(2)}` : ''

  // 优先从 props 中获取 collection 信息（Payload Cell API）
  let collectionSlug = props.collectionConfig?.slug || props.field?.relationTo || props.collection

  // 如果没有从 props 获取到，通过检查预购特有字段自动判断
  if (!collectionSlug) {
    // PreorderProducts 有 orderCount, preorderType 等特有字段
    const isPreorder = rowData?.orderCount !== undefined || rowData?.preorderType !== undefined
    collectionSlug = isPreorder ? 'preorder-products' : 'products'
  }

  const isImage = typeof value === 'string' && value.match(/^https?:\/\/.+/)
  const editUrl = `/admin/collections/${collectionSlug}/${rowData?.id || ''}`

  return (
    <Link
      href={editUrl}
      style={{ display: 'block', width: '100%', textDecoration: 'none', position: 'relative' }}
    >
      <div style={{ position: 'relative', width: '100%', height: '200px' }}>
        {isImage ? (
          <img src={value} alt="商品缩略图" className="thumbnail-img" />
        ) : (
          <div className="no-image">{value || '无图片'}</div>
        )}
        {formattedPrice && (
          <div style={{
            position: 'absolute',
            bottom: '8px',
            right: '8px',
            backgroundColor: 'rgba(0, 0, 0, 0.75)',
            color: 'white',
            padding: '4px 8px',
            borderRadius: '4px',
            fontSize: '14px',
            fontWeight: 'bold',
          }}>
            {formattedPrice}
          </div>
        )}
      </div>
    </Link>
  )
}
