'use client'

import { useState } from 'react'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'

interface MediaGridItem {
  id?: string
  title: string
  imageUrl?: string
}

interface ExpandableMediaGridProps {
  items: Array<string | MediaGridItem>
  imageLabelSuffix: string
  initialCount?: number
  imageClassName?: string
  gridClassName?: string
}

export function ExpandableMediaGrid({ items, imageLabelSuffix, initialCount = 8, imageClassName = 'h-28', gridClassName = 'md:grid-cols-4' }: ExpandableMediaGridProps) {
  const [expanded, setExpanded] = useState(false)
  const visibleItems = expanded ? items : items.slice(0, initialCount)
  const canExpand = items.length > initialCount

  return (
    <>
      <div data-reveal-group className={`grid gap-x-6 gap-y-8 ${gridClassName}`}>
        {visibleItems.map((item) => {
          const mediaItem = typeof item === 'string' ? { title: item } : item
          return (
          <div key={mediaItem.id || mediaItem.title} data-reveal="lift">
            {mediaItem.imageUrl ? (
              <div className={`${imageClassName} rounded-[4px] bg-cover bg-center`} style={{ backgroundImage: `url(${mediaItem.imageUrl})` }} role="img" aria-label={mediaItem.title} />
            ) : (
              <ImagePlaceholder label={`${mediaItem.title}${imageLabelSuffix}`} className={`${imageClassName} rounded-[4px]`} />
            )}
            <div className="mt-3 text-center text-sm font-bold leading-6 text-text-body">{mediaItem.title}</div>
          </div>
          )
        })}
      </div>
      {canExpand && (
        <div className="mt-8 flex justify-center">
          <button
            type="button"
            onClick={() => setExpanded((value) => !value)}
            className="rounded-[4px] border border-line px-5 py-2.5 text-xs font-bold text-muted hover:border-brand hover:text-brand"
          >
            {expanded ? '收起' : '查看更多'}
          </button>
        </div>
      )}
    </>
  )
}
