import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Button } from '@/shared/ui/button'
import { Label } from '@/shared/ui/label'

export function BumperFileUpload({
  channelId,
  templateId,
  kind,
  label,
  hint,
  has,
  accept,
  upload,
  clear,
  onSaved,
  onError,
}: Readonly<{
  channelId: string
  templateId: string
  kind: string
  label: string
  hint: string
  has: boolean
  accept: string
  upload: (id: string, templateId: string, file: File) => Promise<void>
  clear: (id: string, templateId: string) => Promise<void>
  onSaved: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const inputId = `bumper-${kind}-${templateId}`

  const uploadMutation = useMutation({
    mutationFn: (file: File) => upload(channelId, templateId, file),
    onSuccess: onSaved,
    onError,
  })
  const clearMutation = useMutation({
    mutationFn: () => clear(channelId, templateId),
    onSuccess: onSaved,
    onError,
  })
  const busy = uploadMutation.isPending || clearMutation.isPending

  return (
    <div className="flex flex-col gap-1.5">
      <Label>
        {label}{' '}
        <span className={has ? 'text-emerald-500' : 'text-muted-foreground'}>
          {has
            ? `· ${t('admin.channels.bumperFileLoaded')}`
            : `· ${t('admin.channels.bumperFileDefault')}`}
        </span>
      </Label>
      <span className="text-xs text-muted-foreground">{hint}</span>
      <div className="flex items-center gap-2">
        <input
          id={inputId}
          type="file"
          accept={accept}
          className="hidden"
          onChange={(e) => {
            const file = e.target.files?.[0]
            if (file) uploadMutation.mutate(file)
            e.target.value = ''
          }}
        />
        <Button
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => document.getElementById(inputId)?.click()}
        >
          {t('admin.channels.bumperUpload')}
        </Button>
        {has && (
          <Button size="sm" variant="ghost" disabled={busy} onClick={() => clearMutation.mutate()}>
            {t('admin.channels.bumperReset')}
          </Button>
        )}
      </div>
    </div>
  )
}
