import type { FC } from 'react'

import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useLocation } from 'react-router-dom'

import PrefetchLink from '@/components/PrefetchLink'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'
import { dateString } from '@/lib/utils'

import type { WikiPageChange } from '@/types'


const WikiHistoryPage: FC = () => {
  const [changes, setChanges] = useState<WikiPageChange[]> ([])

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

  useEffect (() => {
    void (async () => {
      setChanges (await apiGet<WikiPageChange[]> ('/wiki/changes', { params: id ? { id } : { } }))
    }) ()
  }, [id, location.search])

  return (
      <MainArea>
	<Helmet>
	  <title>{`Wiki 変更履歴 | ${ SITE_TITLE }`}</title>
	</Helmet>

	<PageTitle>Wiki 履歴</PageTitle>

	<table className="table-auto w-full border-collapse">
	  <thead className="border-b-2 border-black dark:border-white">
	    <tr>
	      <th></th>
	      <th className="p-2 text-left">タイトル</th>
	      <th className="p-2 text-left">変更</th>
	      <th className="p-2 text-left">日時</th>
	    </tr>
	  </thead>
	  <tbody>
	    {changes.map (change => (
		<tr key={change.revisionId} className="even:bg-gray-100 dark:even:bg-gray-700">
		  <td className="p-2">
		    {change.pred != null && (
			<PrefetchLink
			    to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.revisionId }`}>
			  差分
			</PrefetchLink>)}
		  </td>
		  <td className="p-2">
		    <PrefetchLink
			to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.revisionId }`}>
		      {change.wikiPage.title}
		    </PrefetchLink>
		    {change.wikiPage.deprecatedAt != null && <span>（廃止）</span>}
		  </td>
		  <td className="p-2">
		    {change.pred == null ? '新規' : '更新'}
		  </td>
		  <td className="p-2">
		    <PrefetchLink to={`/users/${ change.user.id }`}>
		      {change.user.name}
		    </PrefetchLink>
		    <br/>
		    {dateString (change.timestamp)}
		  </td>
		</tr>))}
	  </tbody>
	</table>
      </MainArea>)
}

export default WikiHistoryPage
