import { useEffect, useState } from 'react'

import PostFormTagsArea from '@/components/PostFormTagsArea'
import PostOriginalCreatedTimeField from '@/components/PostOriginalCreatedTimeField'
import Label from '@/components/common/Label'
import { Button } from '@/components/ui/button'
import { apiPut } from '@/lib/api'

import type { FC } from 'react'

import type { Post, Tag } from '@/types'


const tagsToStr = (tags: Tag[]): string => {
  const result: Tag[] = []

  const walk = (tag: Tag) => {
    const { children, ...rest } = tag
    result.push (rest)
    children?.forEach (walk)
  }

  tags.filter (t => t.category !== 'nico').forEach (walk)

  return [...(new Set (result.map (t => t.name)))].join (' ')
}


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


export default (({ post, onSave }: Props) => {
  const [originalCreatedBefore, setOriginalCreatedBefore] =
      useState<string | null> (post.originalCreatedBefore)
  const [originalCreatedFrom, setOriginalCreatedFrom] =
      useState<string | null> (post.originalCreatedFrom)
  const [title, setTitle] = useState (post.title)
  const [tags, setTags] = useState<string> ('')

  const handleSubmit = async () => {
    const data = await apiPut<Post> (
	`/posts/${ post.id }`,
	{ title, tags, original_created_from: originalCreatedFrom,
	  original_created_before: originalCreatedBefore },
	{ headers: { 'Content-Type': 'multipart/form-data' } })
    onSave ({ ...post,
	      title:                  data.title,
	      tags:                   data.tags,
	      originalCreatedFrom:    data.originalCreatedFrom,
	      originalCreatedBefore:  data.originalCreatedBefore } as Post)
  }

  useEffect (() => {
    setTags(tagsToStr (post.tags))
  }, [post])

  return (
      <div className="max-w-xl pt-2 space-y-4">
	{/* タイトル */}
	<div>
	  <Label>タイトル</Label>
	  <input type="text"
		 className="w-full border rounded p-2"
		 value={title}
		 onChange={ev => setTitle (ev.target.value)}/>
	</div>

	{/* タグ */}
	<PostFormTagsArea tags={tags} setTags={setTags}/>

	{/* オリジナルの作成日時 */}
	<PostOriginalCreatedTimeField
	    originalCreatedFrom={originalCreatedFrom}
	    setOriginalCreatedFrom={setOriginalCreatedFrom}
	    originalCreatedBefore={originalCreatedBefore}
	    setOriginalCreatedBefore={setOriginalCreatedBefore}/>

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