import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { BumperTextVariantDto } from '@/shared/api/types'
import { Button } from '@/shared/ui/button'
import { HlsVideo } from '@/shared/ui/hls-video'
import { bumperPreviewPlaylistUrl, renderBumperPreviews } from '../api'

/**
 * Настоящий ffmpeg-рендер примера. Кнопкой, а не автоматически: он занимает несколько секунд,
 * а на каждый ввод в поле его гонять нельзя — для этого есть кадр-предпросмотр в браузере.
 */
export function BumperPreviewPlayer({
  templateId,
  channelId,
  variants,
  onError,
}: Readonly<{
  templateId: string
  channelId: string | null
  variants: BumperTextVariantDto[]
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const [ready, setReady] = useState(false)
  const [bust, setBust] = useState(0)

  const render = useMutation({
    mutationFn: () => renderBumperPreviews(templateId, channelId),
    onSuccess: () => {
      setBust(Date.now())
      setReady(true)
    },
    onError,
  })

  return (
    <>
      <div className="flex flex-wrap items-center gap-2">
        <Button
          size="sm"
          variant="outline"
          disabled={render.isPending}
          onClick={() => render.mutate()}
        >
          {render.isPending ? t('admin.bumpers.rendering') : t('admin.bumpers.render')}
        </Button>
        <span className="text-xs text-muted-foreground">{t('admin.bumpers.renderHint')}</span>
      </div>
      {ready && (
        <div className="grid gap-3 sm:grid-cols-2">
          {[...variants]
            .sort((a, b) => a.position - b.position)
            .map((v) => (
              <div key={v.id} className="flex flex-col gap-1">
                <span className="text-xs text-muted-foreground">{v.name}</span>
                <HlsVideo src={`${bumperPreviewPlaylistUrl(templateId, v.id)}?t=${bust}`} />
              </div>
            ))}
        </div>
      )}
    </>
  )
}
