import type { FC } from 'react'

import MarkdownIt from 'markdown-it'
import { useState } from 'react'
import { Helmet } from 'react-helmet-async'
import MdEditor from 'react-markdown-editor-lite'
import { useLocation, useNavigate } from 'react-router-dom'

import FieldError from '@/components/common/FieldError'
import FormField from '@/components/common/FormField'
import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast'
import { SITE_TITLE } from '@/config'
import { apiPost } from '@/lib/api'
import { canEditContent } from '@/lib/users'
import { inputClass } from '@/lib/utils'
import { useValidationErrors } from '@/lib/useValidationErrors'
import Forbidden from '@/pages/Forbidden'

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

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

const mdParser = new MarkdownIt
const FIXED_WIKI_EDITOR_VIEW = { menu: true, md: true, html: true } as const

// `wiki_editor_mode` is still kept in backend settings, but the common
// settings screen does not expose it at present. Until that UI returns, the
// editor stays on the fixed split view here.

type Props = { user: User | null }

type WikiFormField = 'title' | 'body'


const WikiNewPage: FC<Props> = ({ user }) => {
  const editable = canEditContent (user)

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

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

  const [title, setTitle] = useState (titleQuery)
  const [body, setBody] = useState ('')
  const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
      useValidationErrors<WikiFormField> ()

  const handleSubmit = async () => {
    clearValidationErrors ()

    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' } })
      toast ({ title: '投稿成功!' })
      navigate (`/wiki/${ data.title }`)
    }
    catch (e)
    {
      applyValidationError (e)
      toast ({ title: '投稿失敗', description: '入力を確認してください。' })
    }
  }

  if (!(editable))
    return <Forbidden/>

  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>
	  <FieldError messages={baseErrors}/>

	  {/* タイトル */}
	  {/* TODO: タグ補完 */}
	  <FormField label="タイトル" messages={fieldErrors.title}>
	    {({ describedBy, invalid }) => (
		<input type="text"
		       value={title}
		       onChange={e => setTitle (e.target.value)}
		       aria-describedby={describedBy}
		       aria-invalid={invalid}
		       className={inputClass (invalid)}/>)}
	  </FormField>

	  {/* 本文 */}
	  <FormField label="本文" messages={fieldErrors.body}>
	    {() => (
		<MdEditor value={body}
			  style={{ height: '500px' }}
			  config={{ view: FIXED_WIKI_EDITOR_VIEW }}
			  renderHTML={text => mdParser.render (text)}
			  onChange={({ text }) => setBody (text)}/>)}
	  </FormField>

	  {/* 送信 */}
	  <button onClick={handleSubmit}
		  className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400">
	    追加
	  </button>
	</div>
      </MainArea>)
}

export default WikiNewPage
