import axios from 'axios'
import toCamel from 'camelcase-keys'
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 { API_BASE_URL, SITE_TITLE } from '@/config'
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 () => {
      const res = await axios.get (`${ API_BASE_URL }/wiki/${ id }/diff`, { params: { from, to } })
      setDiff (toCamel (res.data as any, { deep: true }) as WikiPageDiff)
    }) ()
  }, [])

  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>)
}
