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

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)
  const { memberIds: activeHeapMembers } = useActiveHeapMembers()

  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
        const isInActiveHeap = activeHeapMembers.has(photo.id)
        return (
          <button
            key={photo.id}
            ref={isActive ? activeRef : null}
            onClick={() => onSelect(photo.id)}
            className={clsx(
              'relative shrink-0 overflow-hidden rounded-sm will-change-transform transition-[transform,box-shadow,opacity] duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)]',
              isActive && 'scale-90 opacity-100 ring-2 ring-blue-500 ring-offset-2 ring-offset-surface',
              !isActive && isInActiveHeap && 'opacity-100',
              !isActive && !isInActiveHeap && 'opacity-60 hover:opacity-100 hover:ring-1 hover:ring-text-muted/70'
            )}
            style={{ width: CELL_SIZE, height: CELL_SIZE }}
            title={photo.filename}
          >
            <FilmstripThumb photo={photo} />
            {isInActiveHeap && (
              <div className="pointer-events-none absolute inset-0 bg-emerald-500/40" />
            )}
            {isActive && (
              <div className="pointer-events-none absolute inset-0 bg-blue-500/50" />
            )}
          </button>
        )
      })}
    </div>
  )
}

function FilmstripThumb({ photo }: { photo: Photo }) {
  const [loaded, setLoaded] = useState(false)
  const [errored, setErrored] = useState(false)

  useEffect(() => {
    setLoaded(false)
    setErrored(false)
  }, [photo.id])

  return (
    <>
      {!loaded && !errored && (
        <div className="absolute inset-0 animate-pulse bg-bg" />
      )}
      {errored && (
        <div className="absolute inset-0 flex items-center justify-center bg-bg">
          <div className="h-1.5 w-1.5 rounded-full bg-text-muted/50" />
        </div>
      )}
      <img
        src={photosApi.getThumbnailUrl(photo.id, 'small')}
        alt=""
        loading="lazy"
        decoding="async"
        onLoad={() => setLoaded(true)}
        onError={() => setErrored(true)}
        className={clsx(
          'h-full w-full object-cover transition-opacity duration-200',
          loaded ? 'opacity-100' : 'opacity-0',
          // Match the grid's discarded styling so the filmstrip mirrors
          // what the user sees behind the preview.
          photo.is_discarded && 'opacity-50 grayscale'
        )}
      />
    </>
  )
}
