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

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

import type { Thread } from '@/types'


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

  const fetchThreads = async () => {
    setLoading (true)
    try
    {
      const res = await axios.get (`${ API_BASE_URL }/threads`)
      const data = toCamel (res.data as any, { deep: true }) as Thread[]
      const threads = data.filter (t => t.id !== 2)
      setThreads (threads.map (t => ({
	  ...t,
	  createdAt:  (new Date (t.createdAt)).toLocaleString ('ja-JP-u-ca-japanese'),
	  updatedAt:  (new Date (t.updatedAt)).toLocaleString ('ja-JP-u-ca-japanese') })))
    }
    catch
    {
      ;
    }
    setLoading (false)
  }

  useEffect (() => {
    document.title = 'キケッツチャンネル お絵描き掲示板'
    fetchThreads ()
  }, [])

  return (
      <>
	<Accordion allowZeroExpanded
		   onClick={() => setFormOpen (!formOpen)}
		   className="mb-4 mx-auto">
	  <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 > 0
	      ? threads.map (thread => (
		  <div key={thread.id}
		       className="bg-white dark:bg-gray-800 p-3 m-4
				  border border-gray-400 rounded-xl">
		    <div>
		      <Link to={`/threads/${ thread.id }`}>
			<h3>{thread.name}</h3>
		      </Link>
		      <div className="my-2">
			{thread.description?.replaceAll ('\r\n', '\n')
					    .replaceAll ('\r', '\n')
					    .split ('\n')
					    .map ((l, i) => <p key={i}>{l}</p>)}
		      </div>
		    </div>
		    <div className="grid grid-cols-3 justify-between text-sm
				    text-gray-600 dark:text-gray-300">
		      <span className="text-left">{thread.postCount} レス</span>
		      <span className="text-center">{thread.updatedAt} 更新</span>
		      <span className="text-right">{thread.createdAt} 作成</span>
		    </div>
		  </div>))
	      : 'スレないよ（笑）．')}
	</div>
      </>)
}
