import type { FC } from 'react'

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'


const WikiDiffPage: FC = () => {
  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')
  const displayTitle = diff
      ? `${ diff.title }${ diff.deprecatedAt != null ? '（廃止）' : '' }`
      : ''

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

  return (
      <MainArea>
	<Helmet>
	  <title>{`Wiki 差分: ${ displayTitle } | ${ SITE_TITLE }`}</title>
	</Helmet>
	<PageTitle>{displayTitle}</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>)
}

export default WikiDiffPage
