import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type {
  BumperBackground,
  BumperLineDto,
  BumperTemplateDto,
  BumperTextVariantDto,
  BumperTrigger,
} from '@/shared/api/types'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { toast } from '@/shared/ui/toast-store'
import { listInterstitials } from '@/features/admin/interstitials/api'
import { qk } from '@/shared/api/query-keys'
import { removeBumperVariant, updateBumperVariant } from '../api'
import { unknownTokens } from '../placeholders'
import { BumperFramePreview } from './BumperFramePreview'
import { BumperLinesEditor } from './BumperLinesEditor'

const TRIGGERS: BumperTrigger[] = ['OnShowChange', 'BetweenEpisodes', 'Both']
const BACKGROUNDS: BumperBackground[] = ['Template', 'NextPoster', 'NowPoster', 'Clip']

/**
 * Подблок: слева строки, справа постоянный предпросмотр кадра. Предпросмотр не опциональный —
 * без него текст с плейсхолдерами приходится читать как код.
 */
export function BumperVariantEditor({
  template,
  variant,
  canRemove,
  onChanged,
  onError,
}: Readonly<{
  template: BumperTemplateDto
  variant: BumperTextVariantDto
  canRemove: boolean
  onChanged: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  // Ролики грузим списком: их немного, а выбирать подложку удобнее из готового перечня.
  const { data: clips } = useQuery({
    queryKey: qk.interstitials.all,
    queryFn: listInterstitials,
  })
  const [form, setForm] = useState({
    name: variant.name,
    trigger: variant.trigger,
    background: variant.background,
    backgroundClipShowId: variant.backgroundClipShowId,
    weight: variant.weight,
    lines: variant.lines,
  })

  useEffect(() => {
    setForm({
      name: variant.name,
      trigger: variant.trigger,
      background: variant.background,
      backgroundClipShowId: variant.backgroundClipShowId,
      weight: variant.weight,
      lines: variant.lines,
    })
  }, [variant])

  const set = <K extends keyof typeof form>(key: K, value: (typeof form)[K]) =>
    setForm((f) => ({ ...f, [key]: value }))

  const save = useMutation({
    mutationFn: () =>
      updateBumperVariant(template.id, variant.id, { ...form, name: form.name.trim() }),
    onSuccess: () => {
      toast.success(t('settings.saved'))
      onChanged()
    },
    onError,
  })
  const remove = useMutation({
    mutationFn: () => removeBumperVariant(template.id, variant.id),
    onSuccess: onChanged,
    onError,
  })

  const setLines = (lines: BumperLineDto[]) => set('lines', lines)
  const broken = form.lines.some((line) => unknownTokens(line.text).length > 0)
  const empty = form.lines.every((line) => !line.text.trim())

  return (
    <div className="flex flex-col gap-3 rounded-md border border-border bg-background/40 p-3">
      <div className="grid gap-3 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-3">
          <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.bumpers.variantName')}</Label>
              <Input
                value={form.name}
                maxLength={64}
                onChange={(e) => set('name', e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.bumpers.trigger')}</Label>
              <Select
                value={form.trigger}
                onValueChange={(v) => set('trigger', v as BumperTrigger)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {TRIGGERS.map((trigger) => (
                    <SelectItem key={trigger} value={trigger}>
                      {t(`admin.bumpers.triggers.${trigger}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.bumpers.background')}</Label>
              <Select
                value={form.background}
                onValueChange={(v) => set('background', v as BumperBackground)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {BACKGROUNDS.map((background) => (
                    <SelectItem key={background} value={background}>
                      {t(`admin.bumpers.backgrounds.${background}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {/* Ролик-подложка — только при своём источнике фона: в остальных случаях поле было бы
                настройкой, которая ни на что не влияет. */}
            {form.background === 'Clip' && (
              <div className="flex flex-col gap-1.5">
                <Label>{t('admin.bumpers.backgroundClip')}</Label>
                <Select
                  value={form.backgroundClipShowId ?? ''}
                  onValueChange={(v) => set('backgroundClipShowId', v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t('admin.bumpers.pickClip')} />
                  </SelectTrigger>
                  <SelectContent>
                    {(clips ?? []).map((clip) => (
                      <SelectItem key={clip.id} value={clip.id}>
                        {clip.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <span className="text-xs text-muted-foreground">
                  {t('admin.bumpers.backgroundClipHint')}
                </span>
              </div>
            )}
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.bumpers.weight')}</Label>
              <Input
                type="number"
                min={0}
                max={1000}
                value={form.weight}
                onChange={(e) =>
                  set('weight', Math.max(0, Math.round(Number(e.target.value)) || 0))
                }
              />
            </div>
          </div>

          <BumperLinesEditor lines={form.lines} onChange={setLines} />
        </div>

        <div className="flex flex-col gap-1.5">
          <Label>{t('admin.bumpers.framePreview')}</Label>
          <BumperFramePreview
            template={template}
            lines={form.lines}
            showPoster={form.background !== 'Template'}
          />
          <span className="text-xs text-muted-foreground">
            {t('admin.bumpers.framePreviewHint')}
          </span>
        </div>
      </div>

      <div className="flex items-center justify-end gap-2">
        {canRemove && (
          <Button
            size="sm"
            variant="ghost"
            disabled={remove.isPending}
            onClick={() => remove.mutate()}
          >
            {t('common.delete')}
          </Button>
        )}
        <Button
          size="sm"
          variant="outline"
          disabled={save.isPending || !form.name.trim() || broken || empty}
          onClick={() => save.mutate()}
        >
          {t('common.save')}
        </Button>
      </div>
    </div>
  )
}
