import { h, type FunctionComponent } 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 ForgotPasswordForm: FunctionComponent = () => {
  const [{ error, pending, success }, actions] = useRequestState<FetchError>()

  const forgotPassword = useCallback(async (e: SubmitEvent & { currentTarget: HTMLFormElement }) => {
    e.preventDefault()

    actions.pending()

    try {
      await rek.post('/auth/reset-password', {
        email: e.currentTarget.email.value,
      })

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

  return success ? (
    <Message type='success' noMargin>
      Success! Check your inbox to choose a new password.
    </Message>
  ) : (
    <form onSubmit={forgotPassword}>
      {error && (
        <Message type='error'>
          {error.status}: {error.body?.message || error.message}
        </Message>
      )}

      <Input name='email' label='Email' type='email' required />
      <Button disabled={pending}>Forgot Password</Button>
    </form>
  )
}

export default ForgotPasswordForm
