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'

export function BumperPreviewPlayer({
  channelId,
  templateId,
  variants,
  onError,
}: Readonly<{
  channelId: string
  templateId: string
  variants: BumperTextVariantDto[]
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const [ready, setReady] = useState(false)
  const [bust, setBust] = useState(0)

  const render = useMutation({
    mutationFn: () => renderBumperPreviews(channelId, templateId),
    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.channels.bumperPreviewRendering')
            : t('admin.channels.bumperPreview')}
        </Button>
        <span className="text-xs text-muted-foreground">
          {t('admin.channels.bumperPreviewHint')}
        </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(channelId, templateId, v.id)}?t=${bust}`}
                />
              </div>
            ))}
        </div>
      )}
    </>
  )
}
