'use client'

import * as React from 'react'
import { Loader2 } from 'lucide-react'
import { cn } from '../../lib/utils'
import type { SlideData } from './types'

export interface SlideFilmstripProps {
  slides: SlideData[]
  activeId?: string
  onSelect: (id: string) => void
  /** Drag-to-reorder: emits source + target 0-based indices on drop. Enables DnD. */
  onReorder?: (fromIndex: number, toIndex: number) => void
  /** `horizontal` (default) for a bottom strip, `vertical` for a side rail. */
  orientation?: 'horizontal' | 'vertical'
  className?: string
}

/**
 * Scrollable strip of slide thumbnails. Highlights the active slide and emits
 * its id on click. App-agnostic.
 */
export function SlideFilmstrip({
  slides,
  activeId,
  onSelect,
  onReorder,
  orientation = 'horizontal',
  className,
}: SlideFilmstripProps) {
  const dragIndex = React.useRef<number | null>(null)
  return (
    <div
      className={cn(
        'flex gap-2 overflow-auto p-2',
        orientation === 'horizontal' ? 'flex-row' : 'flex-col',
        className
      )}
      role="group"
      aria-label="Slides"
    >
      {slides.map((slide, idx) => {
        const active = slide.id === activeId
        const status = slide.status ?? (slide.imageUrl ? 'ready' : 'pending')
        const dnd = onReorder
          ? {
              draggable: true,
              onDragStart: () => {
                dragIndex.current = idx
              },
              onDragOver: (e: React.DragEvent) => e.preventDefault(),
              onDrop: (e: React.DragEvent) => {
                e.preventDefault()
                const from = dragIndex.current
                dragIndex.current = null
                if (from !== null && from !== idx) onReorder(from, idx)
              },
            }
          : {}
        return (
          <button
            key={slide.id}
            type="button"
            aria-current={active ? 'true' : undefined}
            aria-label={`Slide ${slide.slideNumber}${slide.title ? `: ${slide.title}` : ''}`}
            onClick={() => onSelect(slide.id)}
            {...dnd}
            className={cn(
              'group relative aspect-video w-28 shrink-0 overflow-hidden rounded-md border bg-white text-left transition-all',
              active ? 'border-primary ring-2 ring-primary' : 'border-border hover:border-primary/50'
            )}
          >
            <span className="absolute left-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-white">
              {slide.slideNumber}
            </span>
            {status === 'ready' && slide.imageUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={slide.imageUrl}
                alt={slide.title ?? `Slide ${slide.slideNumber}`}
                className="h-full w-full object-cover"
              />
            ) : (
              <div className="flex h-full w-full items-center justify-center bg-muted text-muted-foreground">
                <Loader2 className={cn('h-4 w-4', status === 'generating' && 'animate-spin')} aria-hidden="true" />
              </div>
            )}
          </button>
        )
      })}
    </div>
  )
}
