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

import PrefetchLink from '@/components/PrefetchLink'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { apiGet } from '@/lib/api'
import { dateString, inputClass } from '@/lib/utils'

import type { FormEvent , FC } from 'react'

import type { WikiPage } from '@/types'


const WikiSearchPage: FC = () => {
  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 (() => {
    void (async () => {
      setResults (await apiGet ('/wiki', { params: { title: '' } }))
    }) ()
  }, [])

  return (
      <MainArea>
	<Helmet>
	  <title>Wiki | {SITE_TITLE}</title>
	</Helmet>

	<div className="max-w-xl">
	  <PageTitle>Wiki</PageTitle>
	  <form onSubmit={handleSearch} className="space-y-2">
	    {/* タイトル */}
	    <FormField label="タイトル">
	      {({ invalid }) => (
		  <input type="text"
			 value={title}
			 onChange={e => setTitle (e.target.value)}
			 className={inputClass (invalid)}/>)}
	    </FormField>

	    {/* 内容 */}
	    <FormField label="内容">
	      {({ invalid }) => (
		  <input type="text"
			 value={text}
			 onChange={e => setText (e.target.value)}
			 className={inputClass (invalid)}/>)}
	    </FormField>

	    {/* 検索 */}
	    <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 className="border-b-2 border-black dark:border-white">
	      <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} className="even:bg-gray-100 dark:even:bg-gray-700">
		    <td className="p-2">
		      <PrefetchLink to={`/wiki/${ encodeURIComponent (page.title) }`}>
			{page.title}
		      </PrefetchLink>
		      {page.deprecatedAt != null && <span>（廃止）</span>}
		    </td>
		    <td className="p-2">
		      {dateString (page.updatedAt)}
		    </td>
		  </tr>))}
	    </tbody>
	  </table>
	</div>
      </MainArea>)
}

export default WikiSearchPage
