import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { Link, useLocation } from 'react-router-dom'

import MainArea from '@/components/layout/MainArea'
import { API_BASE_URL, SITE_TITLE } from '@/config'

import type { WikiPageChange } from '@/types'


export default () => {
  const [changes, setChanges] = useState<WikiPageChange[]> ([])

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

  useEffect (() => {
    void (async () => {
      const res = await axios.get (`${ API_BASE_URL }/wiki/changes`,
				   { params: { ...(id ? { id } : { }) } })
      setChanges (toCamel (res.data as any, { deep: true }) as WikiPageChange[])
    }) ()
  }, [location.search])

  return (
      <MainArea>
	<Helmet>
	  <title>{`Wiki 変更履歴 | ${ SITE_TITLE }`}</title>
	</Helmet>
	<table className="table-auto w-full border-collapse">
	  <thead>
	    <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.sha}>
		  <td>
		    {change.changeType === 'update' && (
			<Link to={`/wiki/${ change.wikiPage.id }/diff?from=${ change.pred }&to=${ change.sha }`}>
			  差分
			</Link>)}
		  </td>
		  <td className="p-2">
		    <Link to={`/wiki/${ encodeURIComponent (change.wikiPage.title) }?version=${ change.sha }`}>
		      {change.wikiPage.title}
		    </Link>
		  </td>
		  <td className="p-2">
		    {(() => {
		      switch (change.changeType)
		      {
		      case 'create':
			return '新規'
		      case 'update':
			return '更新'
		      case 'delete':
			return '削除'
		      }
		    }) ()}
		  </td>
		  <td className="p-2">
		    <Link to={`/users/${ change.user.id }`}>
		      {change.user.name}
		    </Link>
		    <br/>
		    {change.timestamp}
		  </td>
		</tr>))}
	  </tbody>
	</table>
      </MainArea>)
}
