import {useCallback, useState} from 'react'
import {extractErrorMessage} from '../utils/apiErrorHandler'

interface UseApiErrorReturn {
  error: string | null
  setError: (error: string | null) => void
  clearError: () => void
  handleError: (err: unknown) => string
  handleApiErrorWithToast: (err: unknown, toast: any) => void
}

/**
 * Custom hook for handling API errors consistently across components
 * @returns Error handling utilities
 */
export function useApiError(): UseApiErrorReturn {
  const [error, setError] = useState<string | null>(null)

  const clearError = useCallback(() => {
    setError(null)
  }, [])

  const handleError = useCallback((err: unknown): string => {
    const errorMessage = extractErrorMessage(err)
    setError(errorMessage)
    return errorMessage
  }, [])

  const handleApiErrorWithToast = useCallback((err: unknown, toast: any) => {
    const errorMessage = extractErrorMessage(err)
    setError(errorMessage)
    toast.update('error', `Error: ${errorMessage}`)
  }, [])

  return {
    error,
    setError,
    clearError,
    handleError,
    handleApiErrorWithToast
  }
} 