import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'

import { API_BASE_URL } from '@/config'

import type { Thread } from '@/types'


export default () => {
  const navigate = useNavigate ()

  const [disabled, setDisabled] = useState (false)
  const [threadDescription, setThreadDescription] = useState ('')
  const [threadName, setThreadName] = useState ('')

  const submit = async () => {
    if (!(threadName))
      {
	alert ('スレ名入れろよ．')
	return
      }

    try
    {
      setDisabled (true)
      const res = await axios.post (`${ API_BASE_URL }/threads`, { thread:
	  { name: threadName, description: threadDescription } })
      const { id } = toCamel (res.data as any, { deep: true }) as Thread
      navigate (`/threads/${ id }`)
    }
    catch
    {
      setDisabled (false)
    }
    setThreadName ('')
    setThreadDescription ('')
  }

  return (
      <form className="mb-2">
	{/* スレッド名 */}
	<div>
	  <label>スレッド名：</label>
	  <input type="text"
		 className="border border-black"
		 value={threadName}
		 onChange={ev => setThreadName (ev.target.value)} />
	</div>

	{/* スレッド説明 */}
	<div>
	  <label>スレッド説明：</label>
	  <textarea className="border border-black"
		    value={threadDescription}
		    onChange={ev => setThreadDescription (ev.target.value)} />
	</div>

	{/* 作成 */}
	<button type="button"
		disabled={disabled}
		onClick={submit}>
	  スレッド作成
	</button>
      </form>)
}
