import { h, type FunctionComponent } from 'preact'
import { useState } from 'preact/hooks'
import rek from 'rek'
import type { Selectable } from 'kysely'
import type { Object as ObjectType } from '../../../shared/types.db.ts'
import usePromise from '../../shared/hooks/use_promise.ts'
import Head from './head.ts'
import Object from './object.tsx'
import s from './results_page.module.scss'

const ObjectsPage: FunctionComponent = () => {
  const objects = usePromise<(Selectable<ObjectType> & { dimensionName: string })[]>(() => rek('/api/objects'))
  const [currentObject, setCurrentObject] = useState<Selectable<ObjectType> | null>(null)

  return (
    <section>
      <Head>
        <title> : Objekt</title>
      </Head>

      <h1>Objekt</h1>
      <div className={s.objects}>
        {objects.map((object) => (
          <button onClick={() => setCurrentObject(object)}>
            {object.dimensionName}: {object.name}
          </button>
        ))}
      </div>

      {currentObject ? (
        <div>
          <h2>{currentObject}</h2>
          <Object objectId={currentObject.id} />
        </div>
      ) : null}
    </section>
  )
}

export default ObjectsPage
