import axios from 'axios'
import toCamel from 'camelcase-keys'
import { useEffect, useState } from 'react'
import { FaThumbsDown, FaThumbsUp } from 'react-icons/fa'
import { useParams } from 'react-router-dom'

import ThreadCanvas from '@/components/threads/ThreadCanvas'
import { API_BASE_URL } from '@/config'


export default () => {
  const { id } = useParams ()

  const [loading, setLoading] = useState (true)
  const [posts, setPosts] = useState<Post[]> ([])
  const [thread, setThread] = useState<Thread | null> (null)

  useEffect (() => {
    const fetchThread = async () => {
      try
      {
	const res = await axios.get (`${ API_BASE_URL }/threads/${ id }`)
	setThread (toCamel (res.data as any, { deep: true }) as Thread)
      }
      catch
      {
	setThread (null)
      }
    }

    const fetchPosts = async () => {
      setLoading (true)
      try
      {
	const res = await axios.get (`${ API_BASE_URL }/threads/${ id }/posts`)
	const data = toCamel (res.data as any, { deep: true }) as Post[]
	setPosts (data.map (p => ({
	    ...p,
	    createdAt:  (new Date (p.createdAt)).toLocaleString ('ja-JP-u-ca-japanese') })))
      }
      catch
      {
	setPosts ([])
      }
      setLoading (false)
    }

    fetchThread ()
    fetchPosts ()
  }, [])

  useEffect (() => {
    if (!(thread))
      return
    document.title = `${ thread.name } - キケッツチャンネル お絵描き掲示板`
  }, [thread])

  return (
      <>
	<ThreadCanvas />
	{loading ? 'Loading...' : (
	    posts.length > 0
	    ? posts.map (post => (
		<div key={post.id}
		     className="bg-white dark:bg-gray-800 p-3 m-4
				border border-gray-400 rounded-xl
				text-center">
		  <div className="flex justify-between items-center px-2 py-1">
		    <span>{post.postNo}: {post.name || '名なしさん'}</span>
		    <span>{post.createdAt}</span>
		  </div>
		  <div className="flex items-center px-4 pt-1 pb-3">
		    <a className="text-blue-600 dark:text-blue-300 mr-1 whitespace-nowrap"
		       href="#"
		       onClick={async ev => {
			 ev.preventDefault ()
			 try
			 {
			   await axios.post (`${ API_BASE_URL }/posts/${ post.id }/bad`)
			   setPosts (prev => prev.map (p => (p.id === post.id
							     ? { ...p, bad: p.bad + 1 }
							     : p)))
			 }
			 catch
			 {
			   ;
			 }
		       }}>
		      <FaThumbsDown className="inline" /> {post.bad}
		    </a>
		    <div className="h-2 bg-blue-600 dark:bg-blue-300"
			 style={{ width: `${ post.good + post.bad === 0
					     ? 50
					     : post.bad * 100 / (post.good + post.bad) }%` }}>
		    </div>
		    <div className="h-2 bg-red-600 dark:bg-red-300"
			 style={{ width: `${ post.good + post.bad === 0
					     ? 50
					     : post.good * 100 / (post.good + post.bad) }%` }}>
		    </div>
		    <a className="text-red-600 dark:text-red-300 ml-1 whitespace-nowrap"
		       href="#"
		       onClick={async ev => {
			 ev.preventDefault ()
			 try
			 {
			   await axios.post (`${ API_BASE_URL }/posts/${ post.id }/good`)
			   setPosts (prev => prev.map (p => (p.id === post.id
							     ? { ...p, good: p.good + 1 }
							     : p)))
			 }
			 catch
			 {
			   ;
			 }
		       }}>
		      {post.good} <FaThumbsUp className="inline" />
		    </a>
		  </div>
		  <div className="bg-white inline-block border border-black dark:border-white">
		    <img src={`${ API_BASE_URL }${ post.imageUrl }`} />
		  </div>
		</div>))
	    : 'レスないよ（笑）．')}
      </>)
}
