import { useMutation, useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { listGroups } from '@/features/admin/groups/api'
import type {
  BumperTemplateDto,
  JunctionAmountMode,
  JunctionElementDto,
  JunctionElementKind,
} from '@/shared/api/types'
import { qk } from '@/shared/api/query-keys'
import { Button } from '@/shared/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/shared/ui/dialog'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { removeJunctionElement, updateJunctionElement, type JunctionElementBody } from '../api'

const KINDS: JunctionElementKind[] = ['Ad', 'Promo', 'Bumper', 'Filler']
const AMOUNT_MODES: JunctionAmountMode[] = ['Count', 'Duration']

function toBody(element: JunctionElementDto): JunctionElementBody {
  return {
    kind: element.kind,
    groupId: element.groupId,
    bumperTemplateId: element.bumperTemplateId,
    amountMode: element.amountMode,
    amountValue: element.amountValue,
    isRequired: element.isRequired,
    conditions: element.conditions ?? { onlyOnElementChange: false, minMinutesBetween: 0 },
  }
}

/** Параметры одной врезки: тип, источник, сколько её и при каких условиях ставить. */
export function JunctionElementDialog({
  junctionId,
  element,
  bumperTemplates,
  onClose,
  onChanged,
  onError,
}: Readonly<{
  junctionId: string
  element: JunctionElementDto
  bumperTemplates: BumperTemplateDto[]
  onClose: () => void
  onChanged: () => void
  onError: (error: unknown) => void
}>) {
  const { t } = useTranslation()
  const [body, setBody] = useState<JunctionElementBody>(() => toBody(element))
  const { data: groups } = useQuery({ queryKey: qk.groups.all, queryFn: listGroups })

  const patch = (part: Partial<JunctionElementBody>) => setBody((prev) => ({ ...prev, ...part }))

  const save = useMutation({
    mutationFn: () => updateJunctionElement(junctionId, element.id, body),
    onSuccess: () => {
      onChanged()
      onClose()
    },
    onError,
  })
  const remove = useMutation({
    mutationFn: () => removeJunctionElement(junctionId, element.id),
    onSuccess: () => {
      onChanged()
      onClose()
    },
    onError,
  })

  const isBumper = body.kind === 'Bumper'
  const conditions = body.conditions ?? { onlyOnElementChange: false, minMinutesBetween: 0 }

  return (
    <Dialog open onOpenChange={(open) => !open && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('admin.channels.junctionElement')}</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-3 text-sm">
          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.channels.junctionKind')}</Label>
            <select
              className="h-9 rounded-md border border-border bg-transparent px-2"
              value={body.kind}
              onChange={(e) => patch({ kind: e.target.value as JunctionElementKind })}
            >
              {KINDS.map((kind) => (
                <option key={kind} value={kind}>
                  {t(`admin.channels.junctionKinds.${kind}`)}
                </option>
              ))}
            </select>
          </div>

          {isBumper ? (
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.bumperTemplate')}</Label>
              <select
                className="h-9 rounded-md border border-border bg-transparent px-2"
                value={body.bumperTemplateId ?? ''}
                onChange={(e) => patch({ bumperTemplateId: e.target.value || null })}
              >
                <option value="">{t('admin.channels.pickBumperTemplate')}</option>
                {bumperTemplates.map((template) => (
                  <option key={template.id} value={template.id}>
                    {template.name}
                  </option>
                ))}
              </select>
            </div>
          ) : (
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.channels.group')}</Label>
              <select
                className="h-9 rounded-md border border-border bg-transparent px-2"
                value={body.groupId ?? ''}
                onChange={(e) => patch({ groupId: e.target.value || null })}
              >
                <option value="">{t('admin.channels.pickGroup')}</option>
                {(groups ?? []).map((group) => (
                  <option key={group.id} value={group.id}>
                    {group.name} · {group.itemCount}
                  </option>
                ))}
              </select>
            </div>
          )}

          {!isBumper && (
            <>
              <div className="grid grid-cols-2 gap-2">
                <div className="flex flex-col gap-1.5">
                  <Label>{t('admin.channels.junctionAmountMode')}</Label>
                  <select
                    className="h-9 rounded-md border border-border bg-transparent px-2"
                    value={body.amountMode}
                    onChange={(e) => patch({ amountMode: e.target.value as JunctionAmountMode })}
                  >
                    {AMOUNT_MODES.map((mode) => (
                      <option key={mode} value={mode}>
                        {t(`admin.channels.junctionAmountModes.${mode}`)}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="flex flex-col gap-1.5">
                  <Label>
                    {body.amountMode === 'Count'
                      ? t('admin.channels.junctionCount')
                      : t('admin.channels.junctionMinutes')}
                  </Label>
                  <Input
                    type="number"
                    min={1}
                    value={body.amountValue}
                    onChange={(e) => patch({ amountValue: Number(e.target.value) })}
                  />
                </div>
              </div>
              <p className="text-xs text-muted-foreground">
                {t('admin.channels.junctionAmountHint')}
              </p>
            </>
          )}

          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={body.isRequired}
              onChange={(e) => patch({ isRequired: e.target.checked })}
            />
            {t('admin.channels.junctionRequired')}
          </label>

          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={conditions.onlyOnElementChange}
              onChange={(e) =>
                patch({ conditions: { ...conditions, onlyOnElementChange: e.target.checked } })
              }
            />
            {t('admin.channels.junctionOnlyOnChange')}
          </label>

          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.channels.junctionMinInterval')}</Label>
            <Input
              type="number"
              min={0}
              className="w-32"
              value={conditions.minMinutesBetween}
              onChange={(e) =>
                patch({ conditions: { ...conditions, minMinutesBetween: Number(e.target.value) } })
              }
            />
            <p className="text-xs text-muted-foreground">
              {t('admin.channels.junctionMinIntervalHint')}
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button size="sm" variant="destructive" onClick={() => remove.mutate()}>
            {t('common.delete')}
          </Button>
          <Button size="sm" disabled={save.isPending} onClick={() => save.mutate()}>
            {t('common.save')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
