import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { IconSearch, IconHome, IconFileText } from '@tabler/icons-react'
import { api } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'

/**
 * ZIM (Kiwix wiki) skaitytuvas: paieška kairėje + straipsnio turinys
 * dešinėje (iframe iš lokalaus /api/zim/.../content). Veikia offline.
 */
export function ZimReader({ resourceId }: { resourceId: string }) {
  const { t } = useLang()
  const [path, setPath] = useState<string | null>(null)
  // Pradinė užklausa gali ateiti per ?q= (deep-link / dalinimuisi).
  const [q, setQ] = useState(
    () => new URLSearchParams(window.location.search).get('q') ?? ''
  )

  const { data: info } = useQuery({
    queryKey: ['zim-info', resourceId],
    queryFn: () => api.getZimInfo(resourceId),
  })
  const { data: search, isFetching } = useQuery({
    queryKey: ['zim-fts', resourceId, q],
    queryFn: () => api.fullTextZim(resourceId, q),
    enabled: q.trim().length > 0,
  })

  const current = path ?? info?.mainPath ?? null

  return (
    <div className="flex flex-1 gap-3 overflow-hidden">
      {/* Šoninė paieška */}
      <div className="flex w-64 flex-none flex-col rounded-xl border border-arka-border bg-arka-surface">
        <div className="border-b border-arka-border p-2">
          <div className="relative">
            <IconSearch
              size={16}
              className="absolute left-2.5 top-1/2 -translate-y-1/2 text-arka-muted"
            />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder={t('zim.search')}
              className="w-full rounded-lg border border-arka-border bg-arka-bg py-2 pl-8 pr-2 text-sm text-arka-text placeholder:text-arka-muted focus:border-arka-accent focus:outline-none"
            />
          </div>
          <button
            onClick={() => {
              setPath(info?.mainPath ?? null)
              setQ('')
            }}
            className="mt-2 flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-xs font-medium text-arka-muted transition-colors hover:bg-arka-surface-2 hover:text-arka-text"
          >
            <IconHome size={15} /> {t('zim.home')}
            {info && (
              <span className="ml-auto text-[10px]">
                {info.articleCount} {t('zim.articles')}
              </span>
            )}
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-1.5">
          {q.trim().length === 0 ? (
            <p className="p-2 text-xs text-arka-muted">{t('zim.typeToSearch')}</p>
          ) : isFetching ? (
            <p className="p-2 text-xs text-arka-muted">{t('zim.searching')}</p>
          ) : search && search.results.length > 0 ? (
            <>
              {search.truncated && (
                <p className="px-2 pb-1 text-[10px] text-arka-degraded">
                  {t('zim.truncated')}
                </p>
              )}
              <ul className="space-y-0.5">
                {search.results.map((r) => (
                  <li key={r.path}>
                    <button
                      onClick={() => setPath(r.path)}
                      className={`flex w-full flex-col gap-0.5 rounded-md px-2 py-1.5 text-left transition-colors ${
                        current === r.path
                          ? 'bg-arka-accent/15'
                          : 'hover:bg-arka-surface-2'
                      }`}
                    >
                      <span
                        className={`flex items-center gap-2 text-xs font-medium ${
                          current === r.path ? 'text-arka-accent' : 'text-arka-text'
                        }`}
                      >
                        <IconFileText size={14} className="flex-none opacity-60" />
                        <span className="truncate">{r.title}</span>
                      </span>
                      {r.snippet && (
                        <span className="line-clamp-2 pl-6 text-[11px] leading-snug text-arka-muted">
                          {r.snippet}
                        </span>
                      )}
                    </button>
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <p className="p-2 text-xs text-arka-muted">{t('zim.noResults')}</p>
          )}
        </div>
      </div>

      {/* Straipsnio turinys */}
      <div className="flex-1 overflow-hidden rounded-xl border border-arka-border bg-white">
        {current && (
          <iframe
            key={current}
            title="ZIM"
            src={api.zimContentUrl(resourceId, current)}
            sandbox="allow-scripts allow-popups"
            className="h-full w-full border-0"
          />
        )}
      </div>
    </div>
  )
}
