import { useState } from 'react'
import { Bookmark, Check } from '../../lib/icons'
import { useWatchlist } from '../../hooks/use-watchlist'

interface Props {
  itemId: string | null | undefined
  /** Visual style. 'pill' for hero rows, 'icon' for compact corners. */
  variant?: 'pill' | 'icon'
  /** Disable when the item is a TMDB-only result (synthetic id). */
  disabled?: boolean
}

/**
 * Toggles an item in the user's "Watchlist" playlist. Optimistic so the
 * UI flips on click without waiting for the server round-trip.
 */
export default function WatchlistButton({ itemId, variant = 'pill', disabled }: Props) {
  const { isInWatchlist, toggle, isLoading } = useWatchlist()
  const [busy, setBusy] = useState(false)
  const inList = isInWatchlist(itemId)

  async function onClick(e: React.MouseEvent) {
    e.preventDefault()
    e.stopPropagation()
    if (!itemId || busy || disabled) return
    setBusy(true)
    try {
      await toggle(itemId)
    } finally {
      setBusy(false)
    }
  }

  if (variant === 'icon') {
    return (
      <button
        onClick={onClick}
        disabled={disabled || isLoading || !itemId || busy}
        title={inList ? 'Remove from watchlist' : 'Add to watchlist'}
        aria-label={inList ? 'Remove from watchlist' : 'Add to watchlist'}
        className={`w-9 h-9 grid place-items-center rounded-full transition focus-ring ${
          inList
            ? 'bg-accent text-void hover:bg-accent-hover'
            : 'bg-white/10 text-white hover:bg-white/15 ring-1 ring-white/15'
        } ${busy ? 'opacity-60' : ''}`}
      >
        {inList ? <Check size={14} stroke={2.5} /> : <Bookmark size={14} stroke={2} />}
      </button>
    )
  }

  return (
    <button
      onClick={onClick}
      disabled={disabled || isLoading || !itemId || busy}
      className={`inline-flex items-center gap-2 h-11 px-5 rounded-lg text-[13px] font-medium tracking-tight transition-all duration-200 focus-ring ${
        inList
          ? 'bg-accent text-void hover:bg-accent-hover'
          : 'bg-white/10 text-white border border-white/20 backdrop-blur hover:bg-white/15 hover:border-white/30 hover:scale-[1.02] active:scale-[0.98]'
      } ${busy ? 'opacity-60' : ''}`}
    >
      {inList ? <Check size={14} stroke={2.5} /> : <Bookmark size={14} stroke={2} />}
      {inList ? 'In watchlist' : 'Watchlist'}
    </button>
  )
}
