import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { listBumperTemplates } from '@/features/admin/bumpers/api'
import { listGroups } from '@/features/admin/groups/api'
import { qk } from '@/shared/api/query-keys'
import { useApiError } from '@/shared/lib/use-api-error'
import { Button } from '@/shared/ui/button'
import { Card, CardContent } from '@/shared/ui/card'
import { Input } from '@/shared/ui/input'
import { createJunction, listJunctions } from './api'
import { JunctionChain } from './components/JunctionChain'

/**
 * Стыки — общие для всех каналов, как группы. Канал только выбирает, какой стык поставить
 * в слот; собирается стык здесь.
 */
export function JunctionsPanel() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const onError = useApiError()
  const [name, setName] = useState('')

  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 invalidate = () => {
    void queryClient.invalidateQueries({ queryKey: qk.junctions.all })
  }

  const create = useMutation({
    mutationFn: () => createJunction(name.trim()),
    onSuccess: () => {
      setName('')
      invalidate()
    },
    onError,
  })

  return (
    <div className="flex flex-col gap-4">
      <Card>
        <CardContent className="flex flex-col gap-3">
          <p className="text-xs text-muted-foreground">{t('admin.junctions.hint')}</p>
          <div className="flex max-w-md gap-2">
            <Input
              placeholder={t('admin.junctions.newName')}
              value={name}
              maxLength={128}
              onChange={(e) => setName(e.target.value)}
            />
            <Button
              size="sm"
              variant="outline"
              disabled={!name.trim() || create.isPending}
              onClick={() => create.mutate()}
            >
              <Plus className="h-4 w-4" /> {t('common.create')}
            </Button>
          </div>
        </CardContent>
      </Card>

      <div className="flex flex-col gap-3">
        {(junctions ?? []).map((junction) => (
          <JunctionChain
            key={junction.id}
            junction={junction}
            groups={groups}
            bumpers={bumpers}
            onChanged={invalidate}
            onError={onError}
          />
        ))}
        {junctions?.length === 0 && (
          <p className="text-sm text-muted-foreground">{t('admin.junctions.empty0')}</p>
        )}
      </div>
    </div>
  )
}
