import { useMutation } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { BumperTextKind, 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 { removeBumperVariant, updateBumperVariant } from '../api'

export function BumperVariantEditor({
  channelId,
  templateId,
  variant,
  canRemove,
  onChanged,
  onError,
}: Readonly<{
  channelId: string
  templateId: string
  variant: BumperTextVariantDto
  canRemove: boolean
  onChanged: () => void
  onError: (e: unknown) => void
}>) {
  const { t } = useTranslation()
  const [form, setForm] = useState({
    name: variant.name,
    kind: variant.kind,
    nowLabel: variant.nowLabel,
    nextLabel: variant.nextLabel,
    line1: variant.line1,
    line2: variant.line2,
    trigger: variant.trigger,
    weight: variant.weight,
  })

  useEffect(() => {
    setForm({
      name: variant.name,
      kind: variant.kind,
      nowLabel: variant.nowLabel,
      nextLabel: variant.nextLabel,
      line1: variant.line1,
      line2: variant.line2,
      trigger: variant.trigger,
      weight: variant.weight,
    })
  }, [variant])

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

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

  return (
    <div className="flex flex-col gap-2 rounded-md border border-border bg-background/40 p-3">
      <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
        <div className="flex flex-col gap-1.5">
          <Label>{t('admin.channels.bumperVariantName')}</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.channels.bumperTextKind')}</Label>
          <Select value={form.kind} onValueChange={(v) => set('kind', v as BumperTextKind)}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="NowNext">{t('admin.channels.bumperKindNowNext')}</SelectItem>
              <SelectItem value="Free">{t('admin.channels.bumperKindFree')}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>{t('admin.channels.bumperTrigger')}</Label>
          <Select value={form.trigger} onValueChange={(v) => set('trigger', v as BumperTrigger)}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="OnShowChange">
                {t('admin.channels.bumperTriggerOnShowChange')}
              </SelectItem>
              <SelectItem value="BetweenEpisodes">
                {t('admin.channels.bumperTriggerBetweenEpisodes')}
              </SelectItem>
              <SelectItem value="Both">{t('admin.channels.bumperTriggerBoth')}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="flex flex-col gap-1.5">
          <Label>{t('admin.channels.bumperVariantWeight')}</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))}
          />
          <span className="text-xs text-muted-foreground">
            {t('admin.channels.bumperVariantWeightHint')}
          </span>
        </div>
      </div>

      <div className="grid gap-2 sm:grid-cols-2">
        {form.kind === 'NowNext' ? (
          <>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.bumperNowLabel')}</Label>
              <Input
                value={form.nowLabel}
                maxLength={64}
                onChange={(e) => set('nowLabel', e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.bumperNextLabel')}</Label>
              <Input
                value={form.nextLabel}
                maxLength={64}
                onChange={(e) => set('nextLabel', e.target.value)}
              />
            </div>
          </>
        ) : (
          <>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.bumperLine1')}</Label>
              <Input
                value={form.line1}
                maxLength={120}
                onChange={(e) => set('line1', e.target.value)}
              />
            </div>
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.bumperLine2')}</Label>
              <Input
                value={form.line2}
                maxLength={120}
                onChange={(e) => set('line2', e.target.value)}
              />
            </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()}
          onClick={() => save.mutate()}
        >
          {t('common.save')}
        </Button>
      </div>
    </div>
  )
}
