import { h, type FunctionComponent, type TargetedSubmitEvent } from 'preact'
import { useCallback } from 'preact/hooks'
import rek, { type FetchError } from 'rek'

import serializeForm from '../../shared/utils/serialize_form.ts'
import useRequestState from '../../shared/hooks/use_request_state.ts'
import Button from './button.tsx'
import Checkbox from './checkbox.tsx'
import Input from './input.tsx'
import Message from './message.tsx'

const InviteForm: FunctionComponent<{ onCreate?: ANY; roles?: ANY[] }> = ({ onCreate, roles }) => {
  const [{ error, pending, success }, actions] = useRequestState<FetchError>()

  const create = useCallback(async (e: TargetedSubmitEvent<HTMLFormElement>) => {
    e.preventDefault()

    actions.pending()

    try {
      const result = await rek.post('/api/invites', serializeForm(e.currentTarget))

      e.currentTarget.reset()
      actions.success()
      onCreate?.(result)
    } catch (err) {
      actions.error(err as FetchError)
    }
  }, [])

  return (
    <form onSubmit={create}>
      {success && <Message type='success'>Invite sent!</Message>}
      {error && (
        <Message type='error'>
          {error.status || 500} {error.body?.message || error.message}
        </Message>
      )}

      <Input name='email' label='Email' type='email' required />
      {roles && (
        <div>
          {roles.map((role) => (
            <Checkbox key={role.id} name='roles' label={role.name} value={role.id} />
          ))}
        </div>
      )}

      <Button disabled={pending}>Create</Button>
    </form>
  )
}

export default InviteForm
