import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { api, type ResourceType } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'
import { DownloadCard } from './DownloadCard'

/**
 * Katalogo vaizdas: parsiunčia turinį, rodo progresą realiu laiku
 * (polling kas 1 s, kol vyksta atsisiuntimai) ir leidžia atšaukti.
 */
export function CatalogView({ type }: { type?: ResourceType }) {
  const { t } = useLang()
  const qc = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: ['catalog', type ?? 'all'],
    queryFn: () => api.getCatalog(type),
    // Stebim progresą tik kol yra aktyvių atsisiuntimų.
    refetchInterval: (query) => {
      const items = query.state.data?.items ?? []
      const active = items.some(
        (i) => i.task && (i.task.status === 'downloading' || i.task.status === 'queued')
      )
      return active ? 1000 : false
    },
  })

  const start = useMutation({
    mutationFn: (resourceId: string) => api.startDownload(resourceId),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['catalog'] }),
  })
  const cancel = useMutation({
    mutationFn: (id: string) => api.cancelDownload(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['catalog'] }),
  })
  const remove = useMutation({
    mutationFn: (id: string) => api.removeResource(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['catalog'] }),
  })

  if (isLoading) return <p className="text-arka-muted">…</p>
  const items = data?.items ?? []
  if (items.length === 0) return <p className="text-arka-muted">{t('dl.empty')}</p>

  return (
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
      {items.map((item) => (
        <DownloadCard
          key={item.resource.id}
          item={item}
          onStart={(id) => start.mutate(id)}
          onCancel={(id) => cancel.mutate(id)}
          onRemove={(id) => remove.mutate(id)}
          busy={start.isPending && start.variables === item.resource.id}
        />
      ))}
    </div>
  )
}
