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

import useRequestState from '../../shared/hooks/use_request_state.ts'
import Button from './button.tsx'
import Input from './input.tsx'
import Message from './message.tsx'

const RegisterForm = () => {
  const [{ error, pending, success }, actions] = useRequestState<FetchError>()

  const params = location.search ? new URLSearchParams(location.search) : null

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

    actions.pending()

    const form = e.currentTarget

    try {
      await rek.post('/auth/register', {
        email: form.email.value,
        password: form.password.value,
        ...(params
          ? {
              inviteEmail: params.get('email'),
              inviteToken: params.get('token'),
            }
          : {}),
      })

      actions.success()
    } catch (err) {
      actions.error(err as FetchError)
    }
  }, [])

  return success ? (
    <Message type='success' noMargin>
      Success! Go to <a href='/admin/login'>login</a>.
    </Message>
  ) : (
    <form onSubmit={register}>
      {error && (
        <Message type='error'>
          {error.status}: {error.body?.message || error.message}
        </Message>
      )}

      <Input name='email' label='Email' type='email' defaultValue={params?.get('email')} required />
      <Input name='password' label='Password' type='password' required />
      <Input name='confirmPassword' label='Confirm Password' type='password' sameAs='password' required />

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

export default RegisterForm
