import { Image, Typography } from 'antd'
import { useState } from 'react'

import type { UploadedFile } from '@/types/worker-platform'
import { getImageIdentityFromUrl } from '@/utils/image-identity'

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

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

  const hasHiddenItems = Boolean(maxVisible && items.length > maxVisible)
  const visibleItems = hasHiddenItems && !expanded ? items.slice(0, maxVisible) : items

  return (
    <Image.PreviewGroup>
      <div className="image-preview-list">
        {visibleItems.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"
          />
        ))}
        {hasHiddenItems ? (
          <Typography.Link
            className="image-preview-more"
            onClick={() => setExpanded((value) => !value)}
          >
            {expanded ? '收起' : `查看全部（${items.length}）`}
          </Typography.Link>
        ) : null}
      </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) => getImageIdentityFromUrl(item.url)))
  const normalizedUrls = imageUrls
    .map((url) => String(url || '').trim())
    .filter((url) => url && !fileUrlSet.has(getImageIdentityFromUrl(url)))
    .map((url) => ({ url, thumbnailUrl: url, mediumUrl: url }))
  return [...normalizedFiles, ...normalizedUrls]
}
