import axios from 'axios'
import { useState } from 'react'

import TextArea from '@/components/common/TextArea'
import { Button } from '@/components/ui/button'
import { API_BASE_URL } from '@/config'

import type { Post } from '@/types'

type Props = { post:	Post
	       onSave:	(newPost: Post) => void }


export default ({ post, onSave }: Props) => {
  const [title, setTitle] = useState (post.title)
  const [tags, setTags] = useState<string> (post.tags
					    .filter (t => t.category !== 'nico')
					    .map (t => t.name)
					    .join (' '))

  const handleSubmit = async () => {
    const res = await axios.put (`${ API_BASE_URL }/posts/${ post.id }`, { title, tags },
	{ headers: { 'Content-Type':     'multipart/form-data',
		     'X-Transfer-Code':  localStorage.getItem ('user_code') || '' } } )
    const data = res.data as Post
    onSave ({ ...post,
	      title:  data.title,
	      tags:   data.tags } as Post)
  }

  return (
      <div className="max-w-xl pt-2 space-y-4">
	{/* タイトル */}
	<div>
	  <div className="flex gap-2 mb-1">
	    <label className="flex-1 block font-semibold">タイトル</label>
	  </div>
	  <input type="text"
		 className="w-full border rounded p-2"
		 value={title}
		 onChange={e => setTitle (e.target.value)} />
	</div>

	{/* タグ */}
	<div>
	  <label className="block font-semibold">タグ</label>
	  <TextArea value={tags}
		    onChange={ev => setTags (ev.target.value)} />
	</div>

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