import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGFM from 'remark-gfm'

import PrefetchLink from '@/components/PrefetchLink'
import { wikiKeys } from '@/lib/queryKeys'
import remarkWikiAutoLink from '@/lib/remark-wiki-autolink'
import { fetchWikiPages } from '@/lib/wiki'

import type { FC } from 'react'
import type { Components } from 'react-markdown'

type Props = { title: string
	       body?: string }

const mdComponents = { a: (({ href, children }) => (
			      ['/', '.'].some (e => href?.startsWith (e))
			      ? <PrefetchLink to={href!}>{children}</PrefetchLink>
			      : (
				  <a href={href}
				     target="_blank"
				     rel="noopener noreferrer">
				    {children}
				  </a>))) } as const satisfies Components


const WikiBody: FC<Props> = ({ title, body }) => {
  const { data } = useQuery ({
      enabled: Boolean (body),
      queryKey: wikiKeys.index ({ }),
      queryFn: () => fetchWikiPages ({ }) })
  const pageNames = (data ?? []).map (page => page.title).sort ((a, b) => b.length - a.length)

  const remarkPlugins = useMemo (
      () => [() => remarkWikiAutoLink (pageNames), remarkGFM], [pageNames])

  return (
      <ReactMarkdown components={mdComponents} remarkPlugins={remarkPlugins}>
	{body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ encodeURIComponent (title) })。`}
      </ReactMarkdown>)
}

export default WikiBody