import {useState} from 'react'

import {alertError} from '@/lib/dialogs'
import {cleanError} from '@/lib/errors'

// the form submit machine: busy flag + cleaned inline error (or an alert
// when the screen has no error slot); stays busy on success since the
// screen dismisses
export const useSubmitAction = <T>(
  onSubmit: (fields: T) => Promise<void>,
  {alertOnError = false} = {},
) => {
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const submit = async (fields: T) => {
    if (submitting) return
    setSubmitting(true)
    setError(null)
    try {
      await onSubmit(fields)
    } catch (err) {
      if (alertOnError) alertError(err)
      else setError(cleanError(err))
      setSubmitting(false)
    }
  }

  return {submitting, error, submit}
}
