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

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

import type { WikiPageDiff } from '@/types'


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

  const location = useLocation ()

  const [diff, setDiff] = useState<WikiPageDiff | null> (null)

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

  useEffect (() => {
    void (async () => {
      setDiff (await apiGet<WikiPageDiff> (`/wiki/${ id }/diff`, { params: { from, to } }))
    }) ()
  }, [])

  return (
      <MainArea>
	<Helmet>
	  <title>{`Wiki 差分: ${ diff?.title } | ${ SITE_TITLE }`}</title>
	</Helmet>
	<PageTitle>{diff?.title}</PageTitle>
	<div className="prose mx-auto p-4">
	  {diff
	   ? (
	      diff.diff.map (d => (
		  <p className={cn (d.type === 'added' && 'bg-green-200 dark:bg-green-800',
				    d.type === 'removed' && 'bg-red-200 dark:bg-red-800')}>
		    {d.content}
		  </p>)))
	   : 'Loading...'}
	</div>
      </MainArea>)
}
