import { h } from 'preact'
import { useCallback, useEffect } from 'preact/hooks'
import { route } from 'preact-router'
import rek from 'rek'
import type { Selectable } from 'kysely'

import useItemsReducer from '../hooks/use_items_reducer.ts'
import UsersTable from './users_table.tsx'
import PageHeader from './page_header.tsx'
import Section from './section.tsx'

import type { User } from '../../../shared/types.db.ts'

const UsersPage = () => {
  const [users, actions] = useItemsReducer<Selectable<User>>()

  useEffect(() => {
    rek('/api/users' + location.search).then(actions.reset)
  }, [location.search])

  const onSortBy = useCallback((column: string | null) => {
    const searchParams = new URLSearchParams(location.search)

    const newSort = (searchParams.get('sort') || 'id') === column ? '-' + column : column

    route(location.pathname + (newSort !== 'id' ? `?sort=${newSort}` : ''))
  }, [])

  return (
    <section>
      <PageHeader>Users</PageHeader>

      <Section>
        <Section.Heading>List</Section.Heading>

        <Section.Body noPadding>
          <UsersTable users={users} onSortBy={onSortBy} />
        </Section.Body>
      </Section>
    </section>
  )
}

export default UsersPage
