import { Image, Typography } from 'antd'

import type { UploadedFile } from '@/types/worker-platform'

type ImagePreviewListProps = {
  files?: UploadedFile[]
  imageUrls?: string[]
  size?: number
}

export default function ImagePreviewList({
  files = [],
  imageUrls = [],
  size = 56,
}: ImagePreviewListProps) {
  const items = normalizePreviewItems(files, imageUrls)
  if (items.length === 0) {
    return <Typography.Text type="secondary">-</Typography.Text>
  }

  return (
    <Image.PreviewGroup>
      <div className="image-preview-list">
        {items.map((item) => (
          <Image
            key={item.url}
            src={item.thumbnailUrl || item.url}
            preview={{ src: item.mediumUrl || item.url }}
            width={size}
            height={size}
            className="image-preview-item"
          />
        ))}
      </div>
    </Image.PreviewGroup>
  )
}

function normalizePreviewItems(files: UploadedFile[], imageUrls: string[]) {
  const normalizedFiles = files
    .map((file) => ({
      url: file.url || file.mediumUrl || file.thumbnailUrl,
      thumbnailUrl: file.thumbnailUrl || file.url,
      mediumUrl: file.mediumUrl || file.url,
    }))
    .filter((item) => Boolean(item.url))
  const fileUrlSet = new Set(normalizedFiles.map((item) => item.url))
  const normalizedUrls = imageUrls
    .map((url) => String(url || '').trim())
    .filter((url) => url && !fileUrlSet.has(url))
    .map((url) => ({ url, thumbnailUrl: url, mediumUrl: url }))
  return [...normalizedFiles, ...normalizedUrls]
}
