import React from "react"
import Icon from "../icon"
import { useField, useFormContext } from "../../hooks/use-form"

function InlineValidation({ name }) {
  const context = useFormContext()
  const config = context?.config || {}
  const field = useField({ name })

  // To support previous behavior of the validation errors all in one place
  // on the form, we won't show this unless opted in to the new behavior.
  if (!config.validation) return null
  if (!field.touched) return null
  if (!field.error) return null

  return (
    <div className="text-xs" style={{ height: "17px" }} role="alert">
      <Icon icon="exclamation-circle" className="text-red-500 mr-1" />
      {field.error}
    </div>
  )
}

export default InlineValidation
