import { useEffect, useRef } from 'react'
import clsx from 'clsx'
import type { Photo } from '../../types/photo'
import { photos as photosApi } from '../../services/api'

interface PreviewFilmstripProps {
  photos: Photo[]
  currentIndex: number
  onSelect: (id: string) => void
}

const CELL_SIZE = 72

export function PreviewFilmstrip({ photos, currentIndex, onSelect }: PreviewFilmstripProps) {
  const activeRef = useRef<HTMLButtonElement>(null)

  useEffect(() => {
    activeRef.current?.scrollIntoView({
      block: 'nearest',
      inline: 'center',
      behavior: 'smooth',
    })
  }, [currentIndex])

  return (
    <div className="flex h-24 shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-surface px-2 py-2">
      {photos.map((photo, index) => {
        const isActive = index === currentIndex
        return (
          <button
            key={photo.id}
            ref={isActive ? activeRef : null}
            onClick={() => onSelect(photo.id)}
            className={clsx(
              'shrink-0 overflow-hidden rounded-sm transition-all',
              'hover:opacity-100',
              isActive
                ? 'ring-2 ring-primary opacity-100'
                : 'opacity-60'
            )}
            style={{ width: CELL_SIZE, height: CELL_SIZE }}
            title={photo.filename}
          >
            <img
              src={photosApi.getThumbnailUrl(photo.id, 'small')}
              alt={photo.filename}
              loading="lazy"
              className="h-full w-full object-cover"
            />
          </button>
        )
      })}
    </div>
  )
}
