import { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Search, Image, Film, Box, Layers, FileCode2,
  ChevronLeft, ChevronRight, Download, Loader2,
  CheckSquare, Square, X, ZoomIn, Archive, Trash2,
} from 'lucide-react'
import {
  getMediaAssets,
  zipDownloadAssets,
  batchDeleteAssets,
} from '../api/media'
import { toast } from 'sonner'
import type { MediaAssetItem, MediaAssetType } from '../api/media'

// ── Helpers ───────────────────────────────────────────────────────────────────

const formatDate = (iso: string) =>
  new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })

const formatBytes = (bytes: number | null) => {
  if (bytes == null) return null
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

const TYPE_COLORS: Partial<Record<MediaAssetType, string>> = {
  thumbnail:        'badge-gray',
  still:            'badge-blue',
  turntable:        'badge-purple',
  stl_low:          'badge-yellow',
  stl_high:         'badge-orange',
  gltf_geometry:    'badge-green',
  blend_production: 'badge-purple',
}

const ASSET_TYPES_MEDIA = [
  { value: '', label: 'All media' },
  { value: 'still', label: 'Still' },
  { value: 'turntable', label: 'Turntable' },
  { value: 'thumbnail', label: 'Thumbnail' },
]

const ASSET_TYPES_TECHNICAL = [
  { value: 'gltf_geometry', label: 'glTF Geometry' },
  { value: 'blend_production', label: 'Blend (.blend)' },
  { value: 'stl_low', label: 'STL Low' },
  { value: 'stl_high', label: 'STL High' },
]

const CATEGORIES = [
  { value: '', label: 'All categories' },
  { value: 'TRB', label: 'TRB' },
  { value: 'Kugellager', label: 'Kugellager' },
  { value: 'CRB', label: 'CRB' },
  { value: 'Gleitlager', label: 'Gleitlager' },
  { value: 'SRB_TORB', label: 'SRB / TORB' },
  { value: 'Linear_schiene', label: 'Linear-Schiene' },
  { value: 'Anschlagplatten', label: 'Anschlagplatten' },
]

const RENDER_STATUSES = [
  { value: '', label: 'All statuses' },
  { value: 'completed', label: 'Completed' },
  { value: 'failed', label: 'Failed' },
  { value: 'processing', label: 'Processing' },
  { value: 'pending', label: 'Pending' },
]

const PAGE_SIZE_OPTIONS = [25, 50, 100]

// ── TypeIcon ──────────────────────────────────────────────────────────────────

function TypeIcon({ type, size = 32 }: { type: MediaAssetType; size?: number }) {
  if (type === 'still' || type === 'thumbnail') return <Image size={size} className="text-content-muted" />
  if (type === 'turntable') return <Film size={size} className="text-content-muted" />
  if (type === 'stl_low' || type === 'stl_high') return <Box size={size} className="text-content-muted" />
  if (type === 'gltf_geometry') return <FileCode2 size={size} className="text-content-muted" />
  return <Layers size={size} className="text-content-muted" />
}

// ── Lightbox ──────────────────────────────────────────────────────────────────

function Lightbox({ asset, onClose }: { asset: MediaAssetItem; onClose: () => void }) {
  const isVideo = asset.asset_type === 'turntable'
  // No-auth thumbnail endpoint serves image/video directly (no Bearer token needed)
  const mediaSrc = `/api/media/${asset.id}/thumbnail`

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onClose])

  return (
    <div
      className="fixed inset-0 z-50 flex flex-col items-center justify-center"
      style={{ backgroundColor: 'rgba(0,0,0,0.88)' }}
      onClick={onClose}
    >
      {/* Close button */}
      <button
        className="absolute top-4 right-4 p-2 rounded-full text-white transition-colors"
        style={{ backgroundColor: 'rgba(255,255,255,0.15)' }}
        onClick={onClose}
        title="Close (Esc)"
      >
        <X size={20} />
      </button>

      {/* Media */}
      <div
        className="max-w-5xl max-h-[80vh] w-full mx-6 flex items-center justify-center"
        onClick={e => e.stopPropagation()}
      >
        {isVideo ? (
          <video
            src={mediaSrc}
            controls
            autoPlay
            loop
            className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
          />
        ) : asset.thumbnail_url ? (
          <img
            src={asset.thumbnail_url}
            alt={asset.product_name ?? asset.asset_type}
            className="max-w-full max-h-[80vh] object-contain rounded-lg shadow-2xl"
          />
        ) : (
          <div className="flex flex-col items-center gap-4 text-white opacity-60">
            <TypeIcon type={asset.asset_type} size={64} />
            <p className="text-sm">No preview available</p>
          </div>
        )}
      </div>

      {/* Caption */}
      <div
        className="absolute bottom-0 left-0 right-0 px-6 py-4 text-sm text-white"
        style={{ backgroundColor: 'rgba(0,0,0,0.6)' }}
        onClick={e => e.stopPropagation()}
      >
        <div className="flex items-center justify-between max-w-5xl mx-auto">
          <div className="space-y-0.5">
            {asset.product_name && (
              asset.product_id ? (
                <Link to={`/products/${asset.product_id}`} className="font-medium hover:underline">
                  {asset.product_name}
                </Link>
              ) : (
                <p className="font-medium">{asset.product_name}</p>
              )
            )}
            <p className="text-xs opacity-70">
              {asset.asset_type}
              {asset.product_pim_id && ` · ${asset.product_pim_id}`}
              {asset.product_baureihe && ` · ${asset.product_baureihe}`}
              {formatBytes(asset.file_size_bytes) && ` · ${formatBytes(asset.file_size_bytes)}`}
            </p>
          </div>
          {asset.download_url && (
            <a
              href={asset.download_url}
              download
              className="flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-md font-medium transition-colors"
              style={{ backgroundColor: 'rgba(255,255,255,0.2)' }}
              onClick={e => e.stopPropagation()}
            >
              <Download size={13} />
              Download
            </a>
          )}
        </div>
      </div>
    </div>
  )
}

// ── AssetCard ─────────────────────────────────────────────────────────────────

interface AssetCardProps {
  asset: MediaAssetItem
  selected: boolean
  onToggleSelect: (id: string) => void
  onPreview: (asset: MediaAssetItem) => void
}

function AssetCard({ asset, selected, onToggleSelect, onPreview }: AssetCardProps) {
  const isImage = asset.asset_type === 'still' || asset.asset_type === 'thumbnail'
  const isVideo = asset.asset_type === 'turntable'
  // Images need a resolved thumbnail_url; videos always have the no-auth endpoint available
  const isPreviewable = isVideo || (isImage && !!asset.thumbnail_url)
  const typeBadge = TYPE_COLORS[asset.asset_type] ?? 'badge-gray'
  const sizeStr = formatBytes(asset.file_size_bytes)

  return (
    <div
      className={`rounded-lg border overflow-hidden flex flex-col relative group transition-all ${
        selected ? 'border-accent ring-2 ring-accent ring-offset-1' : 'border-border-default'
      }`}
      style={{ backgroundColor: 'var(--color-bg-surface)' }}
    >
      {/* Select checkbox — top-left, always shown when selected, hover otherwise */}
      <button
        className={`absolute top-2 left-2 z-10 rounded p-0.5 transition-all ${
          selected
            ? 'text-accent opacity-100'
            : 'text-white opacity-0 group-hover:opacity-100'
        }`}
        style={{ backgroundColor: selected ? 'rgba(255,255,255,0.9)' : 'rgba(0,0,0,0.45)' }}
        onClick={e => { e.stopPropagation(); onToggleSelect(asset.id) }}
        title={selected ? 'Deselect' : 'Select'}
      >
        {selected ? <CheckSquare size={16} /> : <Square size={16} />}
      </button>

      {/* Preview area */}
      <div
        className="w-full h-40 flex items-center justify-center overflow-hidden relative cursor-pointer"
        style={{ backgroundColor: 'var(--color-bg-surface-alt)' }}
        onClick={() => isPreviewable ? onPreview(asset) : onToggleSelect(asset.id)}
      >
        {isImage && asset.thumbnail_url ? (
          <div className="w-full h-full p-2 flex items-center justify-center">
            <img
              src={asset.thumbnail_url}
              alt={asset.asset_type}
              className="max-w-full max-h-full object-contain"
            />
          </div>
        ) : isVideo ? (
          <video
            src={`/api/media/${asset.id}/thumbnail`}
            preload="metadata"
            muted
            loop
            playsInline
            className="w-full h-full object-cover"
            onMouseEnter={(e) => { e.currentTarget.play().catch(() => {}) }}
            onMouseLeave={(e) => { e.currentTarget.pause(); e.currentTarget.currentTime = 0 }}
          />
        ) : (
          <TypeIcon type={asset.asset_type} />
        )}

        {/* Preview hover overlay */}
        {isPreviewable && (
          <div
            className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none"
            style={{ backgroundColor: 'rgba(0,0,0,0.3)' }}
          >
            {isVideo
              ? <Film size={24} className="text-white" />
              : <ZoomIn size={24} className="text-white" />
            }
          </div>
        )}
      </div>

      {/* Info */}
      <div className="p-3 flex-1 flex flex-col gap-1">
        <div className="flex items-center justify-between gap-1">
          <span className={typeBadge}>
            {asset.asset_type}
          </span>
          {asset.download_url && (
            <a
              href={asset.download_url}
              download
              className="p-1 rounded hover:bg-surface-hover text-content-muted hover:text-content transition-colors"
              title="Download"
              onClick={e => e.stopPropagation()}
            >
              <Download size={14} />
            </a>
          )}
        </div>
        {asset.product_name && (
          asset.product_id ? (
            <Link
              to={`/products/${asset.product_id}`}
              className="text-xs font-medium text-accent hover:text-accent-hover truncate block"
              title={asset.product_name}
              onClick={e => e.stopPropagation()}
            >
              {asset.product_name}
            </Link>
          ) : (
            <p className="text-xs font-medium text-content truncate" title={asset.product_name}>
              {asset.product_name}
            </p>
          )
        )}
        {asset.product_pim_id && (
          <p className="text-xs text-content-muted font-mono truncate">{asset.product_pim_id}</p>
        )}
        {(asset.product_baureihe || asset.product_lagertyp) && (
          <p className="text-xs text-content-muted truncate" title={[asset.product_baureihe, asset.product_lagertyp].filter(Boolean).join(' · ')}>
            {[asset.product_baureihe, asset.product_lagertyp].filter(Boolean).join(' · ')}
          </p>
        )}
        {(asset.product_ebene1 || asset.product_ebene2) && (
          <p className="text-xs truncate" style={{ color: 'var(--color-content-subtle, #9ca3af)' }} title={[asset.product_ebene1, asset.product_ebene2].filter(Boolean).join(' › ')}>
            {[asset.product_ebene1, asset.product_ebene2].filter(Boolean).join(' › ')}
          </p>
        )}
        {(asset.product_name_cad_modell || asset.product_produkt_baureihe) && (
          <p className="text-xs text-content-muted font-mono truncate" title={asset.product_name_cad_modell ?? asset.product_produkt_baureihe ?? ''}>
            {asset.product_name_cad_modell ?? asset.product_produkt_baureihe}
          </p>
        )}
        <div className="flex items-center gap-2 mt-auto pt-1 text-xs text-content-muted">
          <span>{formatDate(asset.created_at)}</span>
          {sizeStr && <span>· {sizeStr}</span>}
        </div>
      </div>
    </div>
  )
}

// ── useDebounce ───────────────────────────────────────────────────────────────

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value)
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
  useEffect(() => {
    if (timer.current) clearTimeout(timer.current)
    timer.current = setTimeout(() => setDebounced(value), delay)
    return () => { if (timer.current) clearTimeout(timer.current) }
  }, [value, delay])
  return debounced
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function MediaBrowserPage() {
  const [searchInput, setSearchInput] = useState('')
  const [assetType, setAssetType] = useState('')
  const [categoryKey, setCategoryKey] = useState('')
  const [renderStatus, setRenderStatus] = useState('')
  const [showTechnical, setShowTechnical] = useState(false)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(50)

  // Selection
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [zipping, setZipping] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const [confirmDelete, setConfirmDelete] = useState(false)

  // Lightbox
  const [previewAsset, setPreviewAsset] = useState<MediaAssetItem | null>(null)

  const q = useDebounce(searchInput, 300)

  // Reset to page 1 when any filter changes; clear selection on page/filter change
  useEffect(() => { setPage(1); setSelected(new Set()) }, [q, assetType, categoryKey, renderStatus, showTechnical, pageSize])
  useEffect(() => { setSelected(new Set()) }, [page])

  // When switching off technical view, clear any technical type selection
  useEffect(() => {
    if (!showTechnical && ASSET_TYPES_TECHNICAL.some(t => t.value === assetType)) {
      setAssetType('')
    }
  }, [showTechnical, assetType])

  const { data, isLoading, isFetching } = useQuery({
    queryKey: ['media-browser', { q, assetType, categoryKey, renderStatus, showTechnical, page, pageSize }],
    queryFn: () => getMediaAssets({
      q: q || undefined,
      asset_type: assetType || undefined,
      category_key: categoryKey || undefined,
      render_status: renderStatus || undefined,
      exclude_technical: !showTechnical && !assetType ? true : undefined,
      page,
      page_size: pageSize,
    }),
    placeholderData: prev => prev,
  })

  const items = data?.items ?? []
  const total = data?.total ?? 0
  const pages = data?.pages ?? 1

  const allSelected = items.length > 0 && items.every(i => selected.has(i.id))

  function toggleSelect(id: string) {
    setSelected(prev => {
      const next = new Set(prev)
      next.has(id) ? next.delete(id) : next.add(id)
      return next
    })
  }

  function toggleSelectAll() {
    if (allSelected) {
      setSelected(new Set())
    } else {
      setSelected(new Set(items.map(i => i.id)))
    }
  }

  const qc = useQueryClient()

  async function handleZipDownload() {
    if (selected.size === 0) return
    setZipping(true)
    try {
      await zipDownloadAssets(Array.from(selected))
    } finally {
      setZipping(false)
    }
  }

  async function handleBatchDelete() {
    if (selected.size === 0) return
    setDeleting(true)
    try {
      const result = await batchDeleteAssets(Array.from(selected))
      toast.success(`Deleted ${result.deleted} asset${result.deleted !== 1 ? 's' : ''}`)
      setSelected(new Set())
      setConfirmDelete(false)
      qc.invalidateQueries({ queryKey: ['media-browser'] })
    } catch {
      toast.error('Failed to delete assets')
    } finally {
      setDeleting(false)
    }
  }

  return (
    <div className="flex flex-col h-full">
      {/* Lightbox */}
      {previewAsset && (
        <Lightbox asset={previewAsset} onClose={() => setPreviewAsset(null)} />
      )}

      {/* Sticky filter bar */}
      <div
        className="sticky top-0 z-20 px-6 py-4 border-b border-border-default"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        <div className="flex items-start gap-3 flex-wrap">
          {/* Header */}
          <div className="flex-1 min-w-0 mr-2">
            <h1 className="text-xl font-semibold text-content">Media Browser</h1>
            <p className="text-sm text-content-muted mt-0.5">
              Browse and download rendered media assets
            </p>
          </div>

          {/* Search */}
          <div className="relative">
            <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-content-muted pointer-events-none" />
            <input
              type="text"
              placeholder="Search name, PIM-ID, Baureihe, Ebene…"
              value={searchInput}
              onChange={e => setSearchInput(e.target.value)}
              className="pl-8 pr-3 py-1.5 text-sm border border-border-default rounded-md focus:outline-none focus:ring-1 focus:ring-accent w-64"
              style={{ backgroundColor: 'var(--color-bg-surface)' }}
            />
          </div>

          {/* Asset type */}
          <select
            value={assetType}
            onChange={e => setAssetType(e.target.value)}
            className="text-sm border border-border-default rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent"
            style={{ backgroundColor: 'var(--color-bg-surface)' }}
          >
            {ASSET_TYPES_MEDIA.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            {showTechnical && (
              <>
                <option disabled>──────────</option>
                {ASSET_TYPES_TECHNICAL.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </>
            )}
          </select>

          {/* Technical files toggle */}
          <label className="flex items-center gap-1.5 text-sm text-content-secondary cursor-pointer select-none">
            <input
              type="checkbox"
              checked={showTechnical}
              onChange={e => setShowTechnical(e.target.checked)}
              className="rounded"
            />
            Technical files
          </label>

          {/* Category */}
          <select
            value={categoryKey}
            onChange={e => setCategoryKey(e.target.value)}
            className="text-sm border border-border-default rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent"
            style={{ backgroundColor: 'var(--color-bg-surface)' }}
          >
            {CATEGORIES.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>

          {/* Render status */}
          <select
            value={renderStatus}
            onChange={e => setRenderStatus(e.target.value)}
            className="text-sm border border-border-default rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-accent"
            style={{ backgroundColor: 'var(--color-bg-surface)' }}
          >
            {RENDER_STATUSES.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>

        {/* Results count + select-all */}
        <div className="flex items-center justify-between mt-2">
          <div className="flex items-center gap-3 text-xs text-content-muted">
            {isFetching && <Loader2 size={12} className="animate-spin" />}
            <span>
              {total === 0 ? 'No assets' : `${total.toLocaleString()} asset${total !== 1 ? 's' : ''}`}
            </span>
            {items.length > 0 && (
              <button
                onClick={toggleSelectAll}
                className="flex items-center gap-1 hover:text-content transition-colors"
              >
                {allSelected ? <CheckSquare size={13} /> : <Square size={13} />}
                {allSelected ? 'Deselect all' : 'Select all on page'}
              </button>
            )}
          </div>
          {selected.size > 0 && (
            <span className="text-xs text-accent font-medium">{selected.size} selected</span>
          )}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto px-6 py-5">
        {isLoading ? (
          <div className="flex items-center justify-center h-64 text-content-muted gap-3">
            <Loader2 size={24} className="animate-spin" />
            <span className="text-sm">Loading assets…</span>
          </div>
        ) : items.length === 0 ? (
          (() => {
            const hasActiveFilters = !!(q || assetType || categoryKey || renderStatus)
            return (
              <div className="flex flex-col items-center justify-center h-64 gap-3" style={{ color: 'var(--color-content-muted)' }}>
                <Image size={48} style={{ opacity: 0.25 }} />
                <p className="text-sm font-medium">
                  {hasActiveFilters ? 'No assets match your filters.' : 'No assets yet — upload a STEP file to get started'}
                </p>
                {hasActiveFilters && (
                  <p className="text-xs text-center max-w-xs">
                    Try adjusting your search or filter settings.
                  </p>
                )}
              </div>
            )
          })()
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {items.map(asset => (
              <AssetCard
                key={asset.id}
                asset={asset}
                selected={selected.has(asset.id)}
                onToggleSelect={toggleSelect}
                onPreview={setPreviewAsset}
              />
            ))}
          </div>
        )}
      </div>

      {/* Floating selection action bar */}
      {selected.size > 0 && (
        <div
          className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 flex items-center gap-3 px-5 py-3 rounded-xl shadow-2xl border border-border-default"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <span className="text-sm font-medium text-content">
            {selected.size} file{selected.size !== 1 ? 's' : ''} selected
          </span>
          <div className="w-px h-5 bg-border-default" />
          <button
            onClick={handleZipDownload}
            disabled={zipping}
            className="flex items-center gap-1.5 text-sm font-medium text-accent hover:text-accent-hover transition-colors disabled:opacity-50"
          >
            {zipping
              ? <><Loader2 size={14} className="animate-spin" /> Preparing…</>
              : <><Archive size={14} /> Download ZIP</>
            }
          </button>
          <div className="w-px h-5 bg-border-default" />
          {confirmDelete ? (
            <div className="flex items-center gap-2">
              <span className="text-sm text-red-500 font-medium">Delete {selected.size} asset{selected.size !== 1 ? 's' : ''}?</span>
              <button
                onClick={handleBatchDelete}
                disabled={deleting}
                className="flex items-center gap-1 text-sm font-medium text-white bg-red-500 hover:bg-red-600 px-2.5 py-1 rounded transition-colors disabled:opacity-50"
              >
                {deleting
                  ? <><Loader2 size={12} className="animate-spin" /> Deleting…</>
                  : <><Trash2 size={12} /> Confirm</>
                }
              </button>
              <button
                onClick={() => setConfirmDelete(false)}
                disabled={deleting}
                className="text-sm text-content-muted hover:text-content transition-colors disabled:opacity-50"
              >
                Cancel
              </button>
            </div>
          ) : (
            <button
              onClick={() => setConfirmDelete(true)}
              className="flex items-center gap-1.5 text-sm font-medium text-red-500 hover:text-red-400 transition-colors"
            >
              <Trash2 size={14} /> Delete
            </button>
          )}
          <div className="w-px h-5 bg-border-default" />
          <button
            onClick={() => { setSelected(new Set()); setConfirmDelete(false) }}
            className="flex items-center gap-1 text-sm text-content-muted hover:text-content transition-colors"
          >
            <X size={14} />
            Clear
          </button>
        </div>
      )}

      {/* Pagination footer */}
      {total > 0 && (
        <div
          className="border-t border-border-default px-6 py-3 flex items-center justify-between gap-4"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          {/* Page size selector */}
          <div className="flex items-center gap-2 text-sm text-content-muted">
            <span>Per page:</span>
            {PAGE_SIZE_OPTIONS.map(size => (
              <button
                key={size}
                onClick={() => setPageSize(size)}
                className={`px-2.5 py-1 rounded text-xs font-medium transition-colors ${
                  pageSize === size
                    ? 'bg-accent text-white'
                    : 'border border-border-default hover:bg-surface-hover text-content'
                }`}
              >
                {size}
              </button>
            ))}
          </div>

          {/* Page nav */}
          <div className="flex items-center gap-2">
            <button
              disabled={page === 1}
              onClick={() => setPage(p => Math.max(1, p - 1))}
              className="p-1.5 rounded border border-border-default hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronLeft size={16} />
            </button>
            <span className="text-sm text-content-muted whitespace-nowrap">
              Page {page} of {pages}
            </span>
            <button
              disabled={page >= pages}
              onClick={() => setPage(p => Math.min(pages, p + 1))}
              className="p-1.5 rounded border border-border-default hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            >
              <ChevronRight size={16} />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
