import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Check, Heart } from '../../lib/icons'
import { useLibrarySelection } from '../../stores/library-selection-store'
import { useBulkMarkPlayed, useBulkToggleFavorite, useRefreshItem } from '../../hooks/use-jellyfin'
import { useWatchlist } from '../../hooks/use-watchlist'

/**
 * Floating toolbar shown over the bottom of the page when at least one
 * library item is multi-selected. Surfaces bulk actions (mark watched,
 * unwatched, favorite, add to watchlist) with optimistic UI - mutations
 * fire all at once and the React Query invalidation refreshes the
 * underlying query.
 */
export default function BatchActionsBar() {
  const selected = useLibrarySelection(s => s.selected)
  const clear = useLibrarySelection(s => s.clear)
  const markPlayed = useBulkMarkPlayed()
  const toggleFav = useBulkToggleFavorite()
  const refreshItem = useRefreshItem()
  const watchlist = useWatchlist()
  const [busy, setBusy] = useState(false)

  const ids = Array.from(selected)
  const count = ids.length
  if (count === 0) return null

  async function run(fn: () => Promise<unknown>) {
    if (busy) return
    setBusy(true)
    try {
      await fn()
      clear()
    } finally {
      setBusy(false)
    }
  }

  return (
    <AnimatePresence>
      {count > 0 && (
        <motion.div
          initial={{ y: 60, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          exit={{ y: 60, opacity: 0 }}
          transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
          className="fixed left-1/2 -translate-x-1/2 bottom-6 z-[70] flex items-center gap-1 px-3 py-2 rounded-full bg-surface/95 backdrop-blur-xl ring-1 ring-border-strong shadow-[0_20px_60px_-15px_rgba(0,0,0,0.85)]"
        >
          <span className="text-[12px] text-text-2 font-medium tabular-nums px-2 mr-1">
            {count} selected
          </span>
          <Action
            label="Mark watched"
            disabled={busy}
            icon={<Check size={13} stroke={2.5} />}
            onClick={() => run(() => markPlayed.mutateAsync({ itemIds: ids, played: true }))}
          />
          <Action
            label="Mark unwatched"
            disabled={busy}
            onClick={() => run(() => markPlayed.mutateAsync({ itemIds: ids, played: false }))}
          />
          <Action
            label="Favorite"
            disabled={busy}
            icon={<Heart size={13} stroke={2} />}
            onClick={() => run(() => toggleFav.mutateAsync({ itemIds: ids, favorite: true }))}
          />
          <Action
            label="Add to watchlist"
            disabled={busy || !watchlist.playlistId}
            onClick={() => run(async () => {
              for (const id of ids) await watchlist.addToWatchlist(id)
            })}
          />
          <Action
            label="Refresh metadata"
            disabled={busy}
            onClick={() => run(async () => {
              for (const id of ids) {
                await refreshItem.mutateAsync({ itemId: id })
              }
            })}
          />
          <button
            onClick={clear}
            aria-label="Clear selection"
            className="ml-1 w-8 h-8 grid place-items-center rounded-full text-text-3 hover:text-text-1 hover:bg-elevated transition focus-ring"
          >
            <X size={13} stroke={2} />
          </button>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

function Action({
  label,
  icon,
  disabled,
  onClick,
}: {
  label: string
  icon?: React.ReactNode
  disabled?: boolean
  onClick: () => void
}) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className="inline-flex items-center gap-1.5 h-9 px-3 rounded-full text-[12px] font-medium tracking-tight text-text-2 hover:text-text-1 hover:bg-elevated transition disabled:opacity-40 focus-ring"
    >
      {icon}
      {label}
    </button>
  )
}
