import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { Image as ImageIcon, Plus } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { imageUrl } from '@/features/admin/images/api'
import { qk } from '@/shared/api/query-keys'
import { useApiError } from '@/shared/lib/use-api-error'
import { Button } from '@/shared/ui/button'
import { useCreateDialog } from '@/shared/lib/use-create-dialog'
import { CreateNameDialog } from '@/shared/ui/create-name-dialog'
import { toast } from '@/shared/ui/toast-store'
import { sortRows, useTableSort } from '@/shared/lib/table-sort'
import { SortHeader } from '@/shared/ui/sortable'
import { createCollection, deleteCollection, fillCollectionPosters, listCollections } from './api'
import { CollectionSuggestions } from './CollectionSuggestions'

export function CollectionsPanel() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const create = useCreateDialog()
  const { sort, toggle } = useTableSort('name', false)

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

  const invalidate = () => queryClient.invalidateQueries({ queryKey: qk.collections.all })
  const onError = useApiError()

  const createMutation = useMutation({
    mutationFn: () => createCollection({ name: create.value.trim() }),
    onSuccess: () => {
      create.close()
      invalidate()
    },
    onError,
  })
  const deleteMutation = useMutation({
    mutationFn: deleteCollection,
    onSuccess: invalidate,
    onError,
  })
  const postersMutation = useMutation({
    mutationFn: () => fillCollectionPosters(),
    onSuccess: (filled) => {
      toast.success(t('admin.collections.postersDone', { count: filled }))
      invalidate()
    },
    onError,
  })

  const rows = sortRows(data ?? [], sort, {
    name: (c) => c.name.toLowerCase(),
    items: (c) => c.itemCount,
    units: (c) => c.unitCount,
  })

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div className="flex flex-col gap-1">
          <h2 className="crt-glow text-xl font-semibold">{t('admin.collections.title')}</h2>
          <p className="text-sm text-muted-foreground">{t('admin.collections.hint')}</p>
        </div>
        <Button size="sm" onClick={create.show}>
          <Plus className="h-4 w-4" />
          {t('common.create')}
        </Button>
      </div>

      <div className="flex flex-wrap items-center gap-2">
        {/* Постер коллекции — обложка её первой части: своей картинки у франшизы нет, а без
            обложки она теряется в списке одинаковых строк. */}
        <Button
          size="sm"
          variant="outline"
          disabled={postersMutation.isPending}
          onClick={() => postersMutation.mutate()}
          title={t('admin.collections.postersHint')}
        >
          <ImageIcon className="h-4 w-4" />
          {t('admin.collections.posters')}
        </Button>
      </div>

      <CollectionSuggestions />

      <div className="crt-panel overflow-x-auto rounded-md">
        <table className="w-full text-sm">
          <thead className="border-b border-border text-left text-muted-foreground">
            <tr>
              <th className="w-16 px-4 py-2 font-medium" />
              <SortHeader
                label={t('admin.collections.name')}
                sortKey="name"
                sort={sort}
                onToggle={toggle}
              />
              <SortHeader
                label={t('admin.collections.parts')}
                sortKey="items"
                sort={sort}
                onToggle={toggle}
              />
              <SortHeader
                label={t('admin.collections.units')}
                sortKey="units"
                sort={sort}
                onToggle={toggle}
              />
              <th className="px-4 py-2 font-medium">{t('common.actions')}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td className="px-4 py-3 text-muted-foreground" colSpan={5}>
                  {t('common.loading')}
                </td>
              </tr>
            )}
            {rows.map((collection) => (
              <tr key={collection.id} className="border-b border-border last:border-0">
                <td className="px-4 py-2">
                  <div className="flex h-12 w-8 items-center justify-center overflow-hidden rounded border border-border bg-muted/30">
                    {collection.posterImageId && (
                      <img
                        src={imageUrl(collection.posterImageId)}
                        alt=""
                        className="h-full w-full object-cover"
                      />
                    )}
                  </div>
                </td>
                <td className="px-4 py-2">
                  <Link
                    to="/admin/collections/$collectionId"
                    params={{ collectionId: collection.id }}
                    className="text-primary hover:underline"
                  >
                    {collection.name}
                  </Link>
                </td>
                <td className="px-4 py-2 text-muted-foreground">{collection.itemCount}</td>
                <td className="px-4 py-2 text-muted-foreground">{collection.unitCount}</td>
                <td className="px-4 py-2">
                  <Button
                    size="sm"
                    variant="destructive"
                    onClick={() => deleteMutation.mutate(collection.id)}
                  >
                    {t('common.delete')}
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {create.open && (
        <CreateNameDialog
          title={t('admin.collections.createTitle')}
          label={t('admin.collections.name')}
          description={t('admin.collections.hint')}
          value={create.value}
          onChange={create.setValue}
          pending={createMutation.isPending}
          onCreate={() => createMutation.mutate()}
          onClose={create.close}
        />
      )}
    </div>
  )
}
