import { useQueryClient } from '@tanstack/react-query'
import { Helmet } from 'react-helmet-async'
import { useLocation, useNavigate } from 'react-router-dom'

import WikiEditForm from '@/components/WikiEditForm'
import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast'
import { SITE_TITLE } from '@/config'
import { apiPost } from '@/lib/api'
import { wikiKeys } from '@/lib/queryKeys'
import Forbidden from '@/pages/Forbidden'

import 'react-markdown-editor-lite/lib/index.css'

import type { User, WikiPage } from '@/types'

type Props = { user: User | null }


export default ({ user }: Props) => {
  if (!(['admin', 'member'].some (r => user?.role === r)))
    return <Forbidden/>

  const location = useLocation ()
  const navigate = useNavigate ()

  const qc = useQueryClient ()

  const query = new URLSearchParams (location.search)
  const titleQuery = query.get ('title') ?? ''

  const handleSubmit = async (title: string, body: string) => {
    const formData = new FormData
    formData.append ('title', title)
    formData.append ('body', body)

    try
    {
      const data = await apiPost<WikiPage> ('/wiki', formData,
	  { headers: { 'Content-Type': 'multipart/form-data' } })
      qc.invalidateQueries ({ queryKey: wikiKeys.root })
      toast ({ title: '投稿成功!' })
      navigate (`/wiki/${ data.title }`)
    }
    catch
    {
      toast ({ title: '投稿失敗', description: '入力を確認してください。' })
    }
  }

  return (
      <MainArea>
	<Helmet>
	  <title>{`新規 Wiki ページ | ${ SITE_TITLE }`}</title>
	</Helmet>
	<div className="max-w-xl mx-auto p-4 space-y-4">
	  <h1 className="text-2xl font-bold mb-2">新規 Wiki ページ</h1>

	  <WikiEditForm
	      title={titleQuery}
	      body=""
	      onSubmit={handleSubmit}/>
	</div>
      </MainArea>)
}
