import {useState} from 'react'

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

// track which row's action is in flight; failures alert by default, or
// surface inline when the screen renders errors in place
export const useBusyAction = ({
  inlineError = false,
  haptic = true,
} = {}) => {
  const [busy, setBusy] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const run = async (
    id: string,
    action: (id: string) => Promise<void>,
  ) => {
    setBusy(id)
    setError(null)
    try {
      await action(id)
      if (haptic) hapticSuccess()
    } catch (err) {
      if (inlineError) setError(cleanError(err))
      else alertError(err)
    } finally {
      setBusy(null)
    }
  }
  return {busy, error, run}
}
