import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { API_BASE_URL } from '@/config'
import { Button } from '@/components/ui/button'

import type { Post, Tag } 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<Tag[]> ([])
  const [tagIds, setTagIds] = useState<number[]> (post.tags.map (t => t.id))

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

  useEffect (() => {
    void (axios.get ('/api/tags')
          .then (res => setTags (res.data))
          .catch (() => toast ({ title: 'タグ一覧の取得失敗' })))
  }, [])

  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>
          <select multiple
                  value={tagIds.map (String)}
                  onChange={e => {
                    const values = Array.from (e.target.selectedOptions).map (o => Number (o.value))
                    setTagIds (values)
                  }}
                  className="w-full p-2 border rounded h-32">
            {tags.map ((tag: Tag) => (
                <option key={tag.id} value={tag.id}>
                  {tag.name}
                </option>))}
          </select>
        </div>

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