import React from "react"
import Label from "../label"
import Input from "../input"
import Stack from "../stack"
import InlineValidation from "../inline-validation"
import { useField, useFormContext } from "../../hooks/use-form"
import PropTypes from "prop-types"

function TextField({
  id,
  name,
  label,
  placeholder,
  type = "text",
  value,
  autoFocus,
  onChange,
  prepend,
  append,
  showLabel = true,
  required,
}) {
  const field = useField({ id, name, value, onChange })

  const state = field.error ? "error" : "default"

  const context = useFormContext() || {}

  return (
    <Stack spacing={2}>
      <Label htmlFor={field.id} visuallyHidden={!showLabel}>{label}</Label>
      <Input
        id={field.id}
        autoFocus={autoFocus}
        name={name}
        value={field.value}
        placeholder={placeholder}
        type={type}
        onBlur={field.onBlur}
        onChange={field.onChange}
        prepend={prepend}
        append={append}
        state={state}
        required={required}
      />

      {context.config?.validation && <InlineValidation name={name} />}
    </Stack>
  )
}

TextField.propTypes = {
  className: PropTypes.string,
  id: PropTypes.string,
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  placeholder: PropTypes.string,
  type: PropTypes.string, // For type, we suggest one of `text`, `password`, `url`, `email`, and suggest `number` less
  value: PropTypes.string,
  autoFocus: PropTypes.string,
  prepend: PropTypes.any,
  append: PropTypes.any,
  onChange: PropTypes.func,
  showLabel: PropTypes.bool,
  required: PropTypes.bool,
}

export default TextField
