import { h } from 'preact'
import { useCallback, useEffect, useState } from 'preact/hooks'
import { route } from 'preact-router'
import rek, { FetchError } from 'rek'

import { useNotifications } from '../contexts/notifications.tsx'
import useItemsReducer from '../hooks/use_items_reducer.ts'
import AdmissionForm from './admission_form.tsx'
import Modal from './modal.tsx'
import AdmissionsTable from './admissions_table.tsx'
import PageHeader from './page_header.tsx'
import Section from './section.tsx'

const AdmissionsPage = () => {
  const { notify } = useNotifications()
  const [admissions, actions] = useItemsReducer()
  const [roles, setRoles] = useState()
  const [editing, setEditing] = useState(null)

  useEffect(() => {
    Promise.all([rek('/api/admissions' + location.search), rek('/api/roles')]).then(([admissions, roles]) => {
      setRoles(roles)
      actions.reset(admissions)
    })
  }, [location.search])

  const onDelete = useCallback(async (id: number) => {
    if (confirm(`Delete admission ${id}?`)) {
      try {
        await rek.delete(`/api/admissions/${id}`)

        actions.del(id)

        notify.success(`Admission ${id} deleted`)
      } catch (err) {
        notify.error((err as FetchError).body?.message || (err as FetchError).toString())
      }
    }
  }, [])

  const onSortBy = useCallback((column: string) => {
    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>Admissions</PageHeader>

      <Section maxWidth='50%'>
        <Section.Heading>Create New Admission</Section.Heading>

        <Section.Body>
          <AdmissionForm onCreate={actions.add} roles={roles} />
        </Section.Body>
      </Section>

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

        <Section.Body noPadding>
          <AdmissionsTable admissions={admissions} onDelete={onDelete} onEdit={setEditing} onSortBy={onSortBy} />
        </Section.Body>
      </Section>

      {editing != null && (
        <Modal onClose={() => setEditing(null)}>
          <AdmissionForm
            onCancel={() => setEditing(null)}
            onUpdate={(admission: ANY) => actions.update(admission.id, admission)}
            admission={admissions.find((admission) => admission.id === editing)}
            roles={roles}
          />
        </Modal>
      )}
    </section>
  )
}

export default AdmissionsPage
