import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { imageUrl } from '@/features/admin/images/api'
import { ImageGallery } from '@/features/admin/images/ImageGallery'
import { Button } from '@/shared/ui/button'
import { Label } from '@/shared/ui/label'
import {
  clearBumperAudio,
  clearBumperBackground,
  setBumperBackground,
  uploadBumperAudio,
} from '../api'

/** Звук блока: его длина и задаёт длительность заставки, без него синтезируется джингл. */
export function BumperAudioField({
  templateId,
  hasAudio,
  onChanged,
  onError,
}: Readonly<{
  templateId: string
  hasAudio: boolean
  onChanged: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const inputId = `bumper-audio-${templateId}`

  const upload = useMutation({
    mutationFn: (file: File) => uploadBumperAudio(templateId, file),
    onSuccess: onChanged,
    onError,
  })
  const clear = useMutation({
    mutationFn: () => clearBumperAudio(templateId),
    onSuccess: onChanged,
    onError,
  })
  const busy = upload.isPending || clear.isPending

  return (
    <div className="flex flex-col gap-1.5">
      <Label>
        {t('admin.bumpers.audio')}{' '}
        <span className={hasAudio ? 'text-emerald-500' : 'text-muted-foreground'}>
          {hasAudio ? `· ${t('admin.bumpers.fileLoaded')}` : `· ${t('admin.bumpers.fileDefault')}`}
        </span>
      </Label>
      <span className="text-xs text-muted-foreground">{t('admin.bumpers.audioHint')}</span>
      <div className="flex items-center gap-2">
        <input
          id={inputId}
          type="file"
          accept="audio/*"
          className="hidden"
          onChange={(e) => {
            const file = e.target.files?.[0]
            if (file) upload.mutate(file)
            e.target.value = ''
          }}
        />
        <Button
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => document.getElementById(inputId)?.click()}
        >
          {t('admin.bumpers.upload')}
        </Button>
        {hasAudio && (
          <Button size="sm" variant="ghost" disabled={busy} onClick={() => clear.mutate()}>
            {t('admin.bumpers.reset')}
          </Button>
        )}
      </div>
    </div>
  )
}

/** Фон блока — из общего реестра изображений, как и всё остальное с картинками. */
export function BumperBackgroundField({
  templateId,
  backgroundImageId,
  onChanged,
  onError,
}: Readonly<{
  templateId: string
  backgroundImageId: string | null
  onChanged: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const [galleryOpen, setGalleryOpen] = useState(false)

  const set = useMutation({
    mutationFn: (imageId: string) => setBumperBackground(templateId, imageId),
    onSuccess: onChanged,
    onError,
  })
  const clear = useMutation({
    mutationFn: () => clearBumperBackground(templateId),
    onSuccess: onChanged,
    onError,
  })

  return (
    <div className="flex flex-col gap-1.5">
      <Label>
        {t('admin.bumpers.background')}{' '}
        <span className={backgroundImageId ? 'text-emerald-500' : 'text-muted-foreground'}>
          {backgroundImageId
            ? `· ${t('admin.bumpers.fileLoaded')}`
            : `· ${t('admin.bumpers.fileDefault')}`}
        </span>
      </Label>
      <span className="text-xs text-muted-foreground">
        {t('admin.bumpers.backgroundFieldHint')}
      </span>
      <div className="flex items-center gap-2">
        {backgroundImageId && (
          <img
            src={imageUrl(backgroundImageId)}
            alt=""
            className="h-10 w-16 shrink-0 rounded border border-border object-cover"
          />
        )}
        <Button size="sm" variant="outline" onClick={() => setGalleryOpen(true)}>
          {t('admin.bumpers.backgroundPick')}
        </Button>
        {backgroundImageId && (
          <Button
            size="sm"
            variant="ghost"
            disabled={clear.isPending}
            onClick={() => clear.mutate()}
          >
            {t('admin.bumpers.reset')}
          </Button>
        )}
      </div>
      <ImageGallery
        open={galleryOpen}
        onOpenChange={setGalleryOpen}
        category="BumperBackground"
        onSelect={(img) => set.mutate(img.id)}
      />
    </div>
  )
}
