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

const ObjectsPage: FunctionComponent = () => {
  const [objects, setObjects] = useState<ObjectType[]>([])
  const [currentObject, setCurrentObject] = useState<ObjectType | null>(null)

  useEffect(() => {
    rek('/api/objects').then((objects: ObjectType[]) => setObjects(objects))
  }, [])

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

      <h1>Objects</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
