import React from "react"
import Radio from "../radio"
import PropTypes from "prop-types"

import { useField } from "../../hooks/use-form"

function RadioField({ id, name, label, value, onChange, checked }) {
  // Value should not be passed into useField hook, because it would
  // override current form's value.
  const field = useField({ id, name, onChange })

  // Radiobutton is checked when cheched state is forced by props (controlled mode)
  // or current form value matches this radio's value
  const checkDefined = typeof (checked) !== "undefined"
  const isChecked = (checkDefined && checked) || (!checkDefined && value === field.value)

  return (
    <div className="flex items-center">
      <Radio
        id={field.id}
        name={name}
        onBlur={field.onBlur}
        onChange={field.onChange}
        checked={isChecked}
        value={value}
      />
      <label className="ml-2 mb-0 font-sans text-gray-900" htmlFor={field.id}>
        {label}
      </label>
    </div>
  )
}

RadioField.propTypes = {
  id: PropTypes.string,
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func,
  checked: PropTypes.bool
}

export default RadioField
