import axios from 'axios'
import toCamel from 'camelcase-keys'
import cn from 'classnames'
import { useEffect, useState } from 'react'
import { Accordion,
	 AccordionItem,
	 AccordionItemButton,
	 AccordionItemHeading,
	 AccordionItemPanel } from 'react-accessible-accordion'
import { FaChevronDown, FaChevronUp } from 'react-icons/fa'

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


export default () => {
  const [loading, setLoading] = useState (true)
  const [threads, setThreads] = useState<Thread[]> ([])
  const [formOpen, setFormOpen] = useState (false)

  useEffect (() => {
    const fetchThreads = async () => {
      try
      {
	const res = await axios.get (`${ API_BASE_URL }/threads`)
	const data = toCamel (res.data as any, { deep: true }) as { threads: Thread[] }
	setThreads (data.threads)
      }
      catch
      {
	;
      }
    }

    setLoading (true)
    fetchThreads ()
    setLoading (false)
  }, [])

  return (
      <>
	<Accordion allowZeroExpanded
		   onClick={() => setFormOpen (!formOpen)}
		   className="mb-4">
	  <AccordionItem>
	    <AccordionItemHeading>
	      <AccordionItemButton className="flex items-center">
		{formOpen ? <FaChevronUp /> : <FaChevronDown />}
		<span className="ml-2">新規スレッド</span>
	      </AccordionItemButton>
	    </AccordionItemHeading>
	    <AccordionItemPanel>
	      <ThreadNewForm />
	    </AccordionItemPanel>
	  </AccordionItem>
	</Accordion>

	<div>
	  {loading ? 'Loading...' : (
	      threads.length
	      ? threads.map (thread => (
		  <div className="bg-white p-2 mb-2 border border-gray-400
				  rounded-xl">
		    <div>
		      <Link to={`/threads/${ thread.id }`}>
			<h3>{thread.title}</h3>
		      </Link>
		      <p>{thread.description}</p>
		    </div>
		    <div className="flex justify-between text-sm text-gray-600">
		      <span>{thread.postCount} レス</span>
		      <span>{thread.updatedAt} 更新</span>
		      <span>{thread.createdAt} 作成</span>
		    </div>
		  </div>))
	      : 'スレないよ（笑）．')}
	</div>
      </>)
}
