import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { addShowsToCollection, listCollections } from '@/features/admin/collections/api'
import { qk } from '@/shared/api/query-keys'
import { useApiError } from '@/shared/lib/use-api-error'
import { Button } from '@/shared/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/shared/ui/dialog'
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'

/** Значение «завести новую» в списке коллекций: пустая строка у Radix зарезервирована под сброс. */
const NEW = '__new__'

/**
 * Куда сложить отмеченные шоу: в существующую франшизу или в новую. Порядок частей сервер
 * расставляет по году — правится он потом перетаскиванием в карточке коллекции.
 */
export function AddToCollectionDialog({
  showIds,
  onClose,
  onAdded,
}: Readonly<{ showIds: string[]; onClose: () => void; onAdded: () => void }>) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const onError = useApiError()
  const [target, setTarget] = useState(NEW)
  const [name, setName] = useState('')

  const { data: collections } = useQuery({
    queryKey: qk.collections.all,
    queryFn: listCollections,
  })

  const add = useMutation({
    mutationFn: () =>
      addShowsToCollection({
        showIds,
        collectionId: target === NEW ? undefined : target,
        newCollectionName: target === NEW ? name.trim() : undefined,
      }),
    onSuccess: (result) => {
      toast.success(
        t('admin.shows.bulk.addedToCollection', { name: result.name, count: result.added }),
      )
      void queryClient.invalidateQueries({ queryKey: qk.collections.all })
      onAdded()
      onClose()
    },
    onError,
  })

  const disabled = add.isPending || (target === NEW && !name.trim())

  return (
    <Dialog open onOpenChange={(open) => !open && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('admin.shows.bulk.toCollection')}</DialogTitle>
          <DialogDescription>{t('admin.shows.bulk.toCollectionHint')}</DialogDescription>
        </DialogHeader>

        <div className="flex flex-col gap-3">
          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.collections.title')}</Label>
            <Select value={target} onValueChange={setTarget}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={NEW}>{t('admin.shows.bulk.newCollection')}</SelectItem>
                {(collections ?? []).map((collection) => (
                  <SelectItem key={collection.id} value={collection.id}>
                    {collection.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {target === NEW && (
            <div className="flex flex-col gap-1.5">
              <Label>{t('admin.collections.name')}</Label>
              <Input
                autoFocus
                value={name}
                maxLength={256}
                onChange={(e) => setName(e.target.value)}
              />
            </div>
          )}
        </div>

        <DialogFooter>
          <Button size="sm" variant="outline" onClick={onClose}>
            {t('common.cancel')}
          </Button>
          <Button size="sm" disabled={disabled} onClick={() => add.mutate()}>
            {t('admin.shows.bulk.addToCollection', { count: showIds.length })}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
