import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet-async'

import PrefetchLink from '@/components/PrefetchLink'
import SectionTitle from '@/components/common/SectionTitle'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'

import type { FormEvent } from 'react'

import type { WikiPage } from '@/types'


export default () => {
  const [title, setTitle] = useState ('')
  const [text, setText] = useState ('')
  const [results, setResults] = useState<WikiPage[]> ([])

  const search = async () => {
    setResults (await apiGet ('/wiki', { params: { title } }))
  }

  const handleSearch = (ev: FormEvent) => {
    ev.preventDefault ()
    search ()
  }

  useEffect (() => {
    search ()
  }, [])

  return (
      <MainArea>
	<Helmet>
	  <title>Wiki | {SITE_TITLE}</title>
	</Helmet>
	<div className="max-w-xl">
	  <SectionTitle>Wiki</SectionTitle>
	  <form onSubmit={handleSearch} className="space-y-2">
	    {/* タイトル */}
	    <div>
	      <label>タイトル：</label><br />
	      <input type="text"
		     value={title}
		     onChange={e => setTitle (e.target.value)}
		     className="border p-1 w-full" />
	    </div>

	    {/* 内容 */}
	    <div>
	      <label>内容：</label><br />
	      <input type="text"
		     value={text}
		     onChange={e => setText (e.target.value)}
		     className="border p-1 w-full" />
	    </div>

	    {/* 検索 */}
	    <div className="py-3">
	      <button type="submit"
		      className="bg-blue-500 text-white px-4 py-2 rounded">
		検索
	      </button>
	    </div>
	  </form>
	</div>

	<div className="mt-4">
	  <table className="table-auto w-full border-collapse">
	    <thead>
	      <tr>
		<th className="p-2 text-left">タイトル</th>
		<th className="p-2 text-left">最終更新</th>
	      </tr>
	    </thead>
	    <tbody>
	      {results.map (page => (
		  <tr key={page.id}>
		    <td className="p-2">
		      <PrefetchLink to={`/wiki/${ encodeURIComponent (page.title) }`}>
			{page.title}
		      </PrefetchLink>
		    </td>
		    <td className="p-2 text-gray-100 text-sm">
		      {page.updatedAt}
		    </td>
		  </tr>))}
	    </tbody>
	  </table>
	</div>
      </MainArea>)
}
