import { useParams, Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import {
  IconArrowLeft,
  IconExternalLink,
  IconBooks,
  IconMap2,
} from '@tabler/icons-react'
import { api, formatBytes, type CatalogItem } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'
import { MapPreview } from '../components/MapPreview'
import { ZimReader } from '../components/ZimReader'

export function Preview() {
  const { id } = useParams()
  const { t } = useLang()
  const { data, isLoading } = useQuery({
    queryKey: ['catalog', 'all'],
    queryFn: () => api.getCatalog(),
  })
  const item = data?.items.find((i) => i.resource.id === id)

  return (
    <div className="flex h-[calc(100vh-8.5rem)] flex-col">
      <Link
        to="/downloads"
        className="mb-3 inline-flex w-fit items-center gap-1.5 text-sm text-arka-muted transition-colors hover:text-arka-text"
      >
        <IconArrowLeft size={16} /> {t('prev.back')}
      </Link>

      {isLoading && <p className="text-arka-muted">…</p>}
      {!isLoading && !item && <p className="text-arka-offline">{t('prev.notFound')}</p>}
      {item && <PreviewBody item={item} />}
    </div>
  )
}

function PreviewBody({ item }: { item: CatalogItem }) {
  const { t, pick } = useLang()
  const r = item.resource
  const fileUrl = `/api/files/${r.type}/${r.filename}`
  const TypeIcon = r.type === 'wiki' ? IconBooks : IconMap2

  if (!item.downloaded) {
    return (
      <div className="rounded-xl border border-arka-border bg-arka-surface p-6">
        <h1 className="text-lg font-bold text-arka-text">{pick(r.name)}</h1>
        <p className="mt-2 text-sm text-arka-muted">{t('prev.notDownloaded')}</p>
        <Link
          to="/downloads"
          className="mt-4 inline-flex rounded-lg bg-arka-accent px-4 py-2 text-sm font-semibold text-arka-bg hover:opacity-90"
        >
          {t('prev.goDownload')}
        </Link>
      </div>
    )
  }

  return (
    <>
      <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-arka-surface-2 text-arka-accent">
            <TypeIcon size={20} stroke={1.6} />
          </span>
          <div>
            <h1 className="text-base font-bold leading-tight text-arka-text">
              {pick(r.name)}
            </h1>
            <div className="text-xs text-arka-muted">
              {t('prev.file')}: {r.filename} · {formatBytes(r.sizeBytes)}
            </div>
          </div>
        </div>
        <a
          href={fileUrl}
          target="_blank"
          rel="noreferrer"
          className="inline-flex items-center gap-1.5 rounded-lg border border-arka-border px-3 py-1.5 text-xs font-medium text-arka-text transition-colors hover:border-arka-accent hover:text-arka-accent"
        >
          <IconExternalLink size={14} /> {t('prev.openFile')}
        </a>
      </div>

      {r.type === 'map' ? (
        <>
          <div className="flex-1 overflow-hidden rounded-xl border border-arka-border">
            <MapPreview url={fileUrl} />
          </div>
          <p className="mt-2 text-xs text-arka-muted">{t('prev.mapHint')}</p>
        </>
      ) : (
        <ZimReader resourceId={r.id} />
      )}
    </>
  )
}
