import { useEffect, useState } from 'react'
import { Link, useLocation, useParams, useNavigate } from 'react-router-dom'
import ReactMarkdown from 'react-markdown'
import axios from 'axios'
import { API_BASE_URL } from '@/config'
import MainArea from '@/components/layout/MainArea'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'

import type { WikiPage } from '@/types'


export default () => {
  const { title } = useParams ()

  const location = useLocation ()
  const navigate = useNavigate ()

  const [wikiPage, setWikiPage] = useState<WikiPage | null | undefined> (undefined)

  const query = new URLSearchParams (location.search)
  const version = query.get ('version')

  useEffect (() => {
    if (/^\d+$/.test (title))
      {
        void (axios.get (`${ API_BASE_URL }/wiki/${ title }`)
              .then (res => navigate (`/wiki/${ res.data.title }`, { replace: true })))
        return
      }

    void (axios.get (`${ API_BASE_URL }/wiki/title/${ encodeURIComponent (title) }`, version && { params: { version } })
          .then (res => {
            setWikiPage (res.data)
            WikiIdBus.set (res.data.id)
          })
          .catch (() => setWikiPage (null)))
  }, [title, location.search])

  return (
      <MainArea>
        {(wikiPage && version) && (
            <div className="text-sm flex gap-3 items-center justify-center border border-gray-700 rounded px-2 py-1 mb-4">
              {wikiPage.pred ? (
                  <Link to={`/wiki/${ title }?version=${ wikiPage.pred }`}
                        className="text-blue-400 hover:underline">
                    &lt; 前
                  </Link>) : <>&lt; 前</>}

              <span>{wikiPage.updated_at}</span>

              {wikiPage.succ ? (
                  <Link to={`/wiki/${ title }?version=${ wikiPage.succ }`}
                        className="text-blue-400 hover:underline">
                    後 &gt;
                  </Link>) : <>後 &gt;</>}
            </div>)}
        <h1>{title}</h1>
        <div className="prose mx-auto p-4">
          {wikiPage === undefined ? 'Loading...' : (
              <>
                <ReactMarkdown components={{ a: (
                    ({ href, children }) => (['/', '.'].some (e => href?.startsWith (e))
                                             ? <Link to={href!}>{children}</Link>
                                             : <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>)) }}>
                  {wikiPage?.body || `このページは存在しません。[新規作成してください](/wiki/new?title=${ title })。`}
                </ReactMarkdown>
              </>)}
        </div>
      </MainArea>)
}
