import { motion } from 'framer-motion'
import type { ButtonHTMLAttributes, PointerEvent as ReactPointerEvent } from 'react'
import {
  Play,
  Pause,
  SkipBack,
  SkipForward,
  RotateCcw,
  RotateCw,
  Volume1,
  Volume2,
  VolumeX,
  Maximize,
  Minimize,
} from '../../lib/icons'
import ChapterTicks from './ChapterTicks'
import TrickplayThumbnail from './TrickplayThumbnail'
import { loadBookmarks } from '../../lib/bookmarks'
import type { BaseItemDto } from '../../api/types'

interface Props {
  itemId: string | undefined
  item: BaseItemDto | null | undefined
  serverUrl: string
  token: string
  duration: number
  currentTime: number
  bufferedPercent: number
  playedPercent: number
  scrubPercent: number | null
  isPaused: boolean
  isMuted: boolean
  isFullscreen: boolean
  volume: number
  loopA: number | null
  loopB: number | null
  chapters: { StartPositionTicks?: number | null; Name?: string | null; ImageTag?: string | null }[]
  bookmarksRefreshKey: number
  previousItem: BaseItemDto | null | undefined
  nextItem: BaseItemDto | null | undefined
  itemType: string | null | undefined
  queueActive: boolean
  onScrubPointerMove: (e: ReactPointerEvent<HTMLDivElement>) => void
  onScrubPointerLeave: () => void
  onScrubPointerDown: (e: ReactPointerEvent<HTMLDivElement>) => void
  onScrubPointerUp: (e: ReactPointerEvent<HTMLDivElement>) => void
  onChapterJump: (seconds: number) => void
  onTogglePlay: () => void
  onPrevious: () => void
  onNext: () => void
  onBack10: () => void
  onForward10: () => void
  onToggleMute: () => void
  onVolumeChange: (v: number) => void
  onToggleFullscreen: () => void
}

export default function PlayerBottomBar({
  itemId,
  item,
  serverUrl,
  token,
  duration,
  currentTime,
  bufferedPercent,
  playedPercent,
  scrubPercent,
  isPaused,
  isMuted,
  isFullscreen,
  volume,
  loopA,
  loopB,
  chapters,
  bookmarksRefreshKey,
  previousItem,
  nextItem,
  itemType,
  queueActive,
  onScrubPointerMove,
  onScrubPointerLeave,
  onScrubPointerDown,
  onScrubPointerUp,
  onChapterJump,
  onTogglePlay,
  onPrevious,
  onNext,
  onBack10,
  onForward10,
  onToggleMute,
  onVolumeChange,
  onToggleFullscreen,
}: Props) {
  const VolumeIcon = isMuted || volume === 0 ? VolumeX : volume < 0.5 ? Volume1 : Volume2
  const isEpisode = itemType === 'Episode'
  const showPrev = !!(previousItem || queueActive || isEpisode)
  const showNext = !!(nextItem || queueActive || isEpisode)
  const trickplay = (item as { Trickplay?: unknown } | null | undefined)?.Trickplay

  return (
    <motion.div
      initial={{ y: 10, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      exit={{ y: 10, opacity: 0 }}
      transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
      data-player-bottom-bar
      className="bg-gradient-to-t from-black/85 via-black/40 to-transparent pt-12 pb-5 px-7 pointer-events-auto"
    >
      {/* Scrubber */}
      <div
        className="relative h-5 mb-1 cursor-pointer group/scrub touch-none"
        onPointerMove={onScrubPointerMove}
        onPointerLeave={onScrubPointerLeave}
        onPointerDown={onScrubPointerDown}
        onPointerUp={onScrubPointerUp}
        onPointerCancel={onScrubPointerUp}
      >
        {/* Track */}
        <div className="absolute left-0 right-0 top-1/2 -translate-y-1/2 h-1 group-hover/scrub:h-1.5 transition-all duration-150 rounded-full bg-white/15 overflow-hidden">
          <div
            className="absolute left-0 top-0 bottom-0 bg-white/25 rounded-full transition-all duration-300"
            style={{ width: `${bufferedPercent}%` }}
          />
          <div
            className="absolute left-0 top-0 bottom-0 bg-accent rounded-full"
            style={{ width: `${playedPercent}%` }}
          />
          {scrubPercent !== null && (
            <div
              className="absolute left-0 top-0 bottom-0 bg-white/15 rounded-full pointer-events-none"
              style={{ width: `${scrubPercent * 100}%` }}
            />
          )}
          {duration > 0 && loopA != null && loopB != null && loopB > loopA && (
            <div
              className="absolute top-0 bottom-0 bg-accent/40 ring-1 ring-accent/60 pointer-events-none"
              style={{
                left: `${(loopA / duration) * 100}%`,
                width: `${((loopB - loopA) / duration) * 100}%`,
              }}
            />
          )}
        </div>
        {/* Bookmark dots */}
        {itemId && duration > 0 && loadBookmarks(itemId).map(bm => {
          void bookmarksRefreshKey
          const left = (bm.positionSec / duration) * 100
          if (left < 0 || left > 100) return null
          return (
            <span
              key={bm.id}
              title={bm.note || `Bookmark @ ${bm.positionSec.toFixed(0)}s`}
              className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-cool ring-2 ring-cool/40 pointer-events-none"
              style={{ left: `${left}%` }}
            />
          )
        })}
        {/* Chapter ticks */}
        {itemId && (
          <ChapterTicks
            chapters={chapters}
            duration={duration}
            onJump={onChapterJump}
          />
        )}
        {/* Thumb */}
        <motion.div
          className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-3.5 h-3.5 rounded-full bg-accent shadow-[0_0_12px_rgba(245,182,66,0.7)] opacity-0 group-hover/scrub:opacity-100 transition-opacity duration-150 pointer-events-none"
          style={{ left: `${playedPercent}%` }}
        />
        {/* Time tooltip + trickplay */}
        {scrubPercent !== null && (
          <div
            className="absolute bottom-6 -translate-x-1/2 flex flex-col items-center gap-1 pointer-events-none"
            style={{ left: `${scrubPercent * 100}%` }}
          >
            {!!trickplay && item && (
              <TrickplayThumbnail
                item={item}
                serverUrl={serverUrl}
                token={token}
                timeSec={scrubPercent * duration}
                displayWidth={200}
              />
            )}
            <div className="px-2 py-1 rounded-md bg-black/85 text-white text-[11px] font-medium tabular-nums whitespace-nowrap">
              {formatTime(scrubPercent * duration)}
            </div>
          </div>
        )}
      </div>

      {/* Controls row */}
      <div className="flex items-center justify-between mt-2">
        <div className="flex items-center gap-1">
          {showPrev && (
            <button
              onClick={onPrevious}
              disabled={!previousItem?.Id}
              className="w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring disabled:opacity-30 disabled:hover:bg-transparent"
              aria-label="Previous"
              title={previousItem ? `Previous: ${previousItem.Name || ''}` : 'No previous'}
            >
              <SkipBack size={16} fill="currentColor" />
            </button>
          )}
          <button
            onClick={onTogglePlay}
            className="w-11 h-11 rounded-full grid place-items-center text-white hover:bg-white/10 transition-all duration-150 focus-ring"
            aria-label={isPaused ? 'Play' : 'Pause'}
          >
            {isPaused ? (
              <Play size={20} fill="currentColor" className="translate-x-0.5" />
            ) : (
              <Pause size={20} fill="currentColor" />
            )}
          </button>
          {showNext && (
            <button
              onClick={onNext}
              disabled={!nextItem?.Id || nextItem.Id === item?.Id}
              className="w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring disabled:opacity-30 disabled:hover:bg-transparent"
              aria-label="Next"
              title={nextItem ? `Next: ${nextItem.Name || ''}` : 'No next'}
            >
              <SkipForward size={16} fill="currentColor" />
            </button>
          )}
          <button
            onClick={onBack10}
            className="w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring relative"
            aria-label="Back 10 seconds"
          >
            <RotateCcw size={17} />
            <span className="absolute text-[8px] font-bold tabular-nums">10</span>
          </button>
          <button
            onClick={onForward10}
            className="w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring relative"
            aria-label="Forward 10 seconds"
          >
            <RotateCw size={17} />
            <span className="absolute text-[8px] font-bold tabular-nums">10</span>
          </button>

          {/* Volume cluster */}
          <div className="group/vol flex items-center ml-1">
            <button
              onClick={onToggleMute}
              className="w-9 h-9 grid place-items-center text-white/85 hover:text-white rounded-full hover:bg-white/10 transition-colors focus-ring"
              aria-label={isMuted ? 'Unmute' : 'Mute'}
            >
              <VolumeIcon size={17} />
            </button>
            <div className="w-0 group-hover/vol:w-24 overflow-x-clip overflow-y-visible transition-all duration-300 ease-out">
              <input
                type="range"
                min={0}
                max={1}
                step={0.01}
                value={isMuted ? 0 : volume}
                onChange={e => onVolumeChange(Number(e.target.value))}
                className="slider w-22 ml-1.5"
              />
            </div>
          </div>

          {/* Time */}
          <div className="ml-3 text-[12px] text-white/85 font-medium tabular-nums">
            {formatTime(currentTime)}
            <span className="text-white/40 mx-1.5">/</span>
            <span className="text-white/55">{formatTime(duration)}</span>
          </div>
        </div>

        <div className="flex items-center gap-1">
          <ChromeButton onClick={onToggleFullscreen} aria-label={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
            {isFullscreen ? <Minimize size={17} /> : <Maximize size={17} />}
          </ChromeButton>
        </div>
      </div>
    </motion.div>
  )
}

function ChromeButton({
  children,
  className = '',
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement>) {
  return (
    <button
      {...props}
      className={`w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring ${className}`}
    >
      {children}
    </button>
  )
}

function formatTime(seconds: number): string {
  if (!seconds || !isFinite(seconds)) return '0:00'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  return `${m}:${s.toString().padStart(2, '0')}`
}
