import { useMutation, useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { ExternalLink } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { listBumperTemplates } from '@/features/admin/bumpers/api'
import { listGroups } from '@/features/admin/groups/api'
import { listJunctions } from '@/features/admin/junctions/api'
import { formatClock } from '@/features/admin/interstitials/format'
import { stepSeconds, toSteps } from '@/features/admin/junctions/lib'
import type { JunctionTemplateDto, ScheduleTemplateDto } from '@/shared/api/types'
import { qk } from '@/shared/api/query-keys'
import { Button } from '@/shared/ui/button'
import { Label } from '@/shared/ui/label'
import { updateTemplate } from '../api'
import { CollapsibleCard } from './CollapsibleCard'

/**
 * Стыки канала: что канал выбрал, а не как стык устроен. Сами стыки общие и правятся в своём
 * разделе — держать их редактор ещё и здесь значило бы иметь два места для одного и того же.
 */
export function JunctionsCard({
  template,
  bare,
  onChanged,
  onError,
}: Readonly<{
  template: ScheduleTemplateDto | undefined
  bare?: boolean
  onChanged: () => void
  onError: (error: unknown) => void
}>) {
  const { t } = useTranslation()

  const { data: junctions } = useQuery({ queryKey: qk.junctions.all, queryFn: listJunctions })
  const { data: groups } = useQuery({ queryKey: qk.groups.all, queryFn: listGroups })
  const { data: bumpers } = useQuery({ queryKey: qk.bumpers.all, queryFn: listBumperTemplates })

  const defaultMutation = useMutation({
    mutationFn: (junctionId: string | null) =>
      updateTemplate(template!.id, {
        name: template!.name,
        fallbackGroupId: template!.fallbackGroupId,
        defaultJunctionId: junctionId,
        rules: template!.rules,
      }),
    onSuccess: onChanged,
    onError,
  })

  // Что реально играет в этом канале: стык по умолчанию плюс всё, на что ссылаются слоты.
  const usedIds = new Set<string>()
  if (template?.defaultJunctionId) usedIds.add(template.defaultJunctionId)
  for (const layer of template?.layers ?? [])
    for (const slot of layer.slots) {
      if (slot.junctionBetweenId) usedIds.add(slot.junctionBetweenId)
      if (slot.junctionAfterId) usedIds.add(slot.junctionAfterId)
    }
  const used = (junctions ?? []).filter((j) => usedIds.has(j.id))

  const summary = (junction: JunctionTemplateDto) => {
    const steps = toSteps(junction.elements)
    const total = steps.reduce((sum, step) => sum + stepSeconds(step, groups, bumpers).seconds, 0)
    const chain = steps
      .map((step) => step.elements.map((e) => t(`admin.junctions.kinds.${e.kind}`)).join(' | '))
      .join(' → ')
    return { chain: chain || t('admin.junctions.empty'), total }
  }

  return (
    <CollapsibleCard title={t('admin.channels.junctions')} bare={bare}>
      <div className="flex flex-col gap-4">
        <p className="text-xs text-muted-foreground">{t('admin.channels.junctionsHint')}</p>

        {template && (
          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.channels.defaultJunction')}</Label>
            <select
              className="h-9 max-w-xs rounded-md border border-border bg-transparent px-2 text-sm"
              value={template.defaultJunctionId ?? ''}
              onChange={(e) => defaultMutation.mutate(e.target.value || null)}
            >
              <option value="">{t('admin.channels.noJunction')}</option>
              {(junctions ?? []).map((junction) => (
                <option key={junction.id} value={junction.id}>
                  {junction.name}
                </option>
              ))}
            </select>
          </div>
        )}

        <div className="flex flex-col gap-2">
          <p className="text-sm font-medium">{t('admin.channels.junctionsUsed')}</p>
          {used.length === 0 && (
            <p className="text-xs text-muted-foreground">{t('admin.channels.junctionsNoneUsed')}</p>
          )}
          {used.map((junction) => {
            const { chain, total } = summary(junction)
            return (
              <div
                key={junction.id}
                className="flex flex-wrap items-center gap-2 rounded-md border border-border px-3 py-2 text-xs"
              >
                <span className="font-medium">{junction.name}</span>
                <span className="text-muted-foreground">{chain}</span>
                <span className="ml-auto text-muted-foreground">≈ {formatClock(total)}</span>
              </div>
            )
          })}
        </div>

        <div>
          <Button asChild size="sm" variant="outline">
            <Link to="/admin/junctions">
              <ExternalLink className="h-4 w-4" /> {t('admin.channels.openJunctionEditor')}
            </Link>
          </Button>
        </div>
      </div>
    </CollapsibleCard>
  )
}
