import React from "react"
import Text from "../text"
import ToggleInput from "../toggle-input"
import Stack from "../stack"
import InlineValidation from "../inline-validation"
import { useField, useFormContext } from "../../hooks/use-form"
import PropTypes from "prop-types"

function ToggleField({ id, name, label, description, value, onChange }) {
  const field = useField({ id, name, value, onChange })

  const context = useFormContext() || {}

  return (
    <div className="flex gap-8">
      <ToggleInput
        id={field.id}
        name={name}
        onBlur={field.onBlur}
        onChange={field.onChange}
        checked={field.value}
        aria-describedby={`${field.id}-desc`}
        className="flex-shrink-0"
      />
      <Stack spacing={2}>
        <Text as="label" htmlFor={field.id} weight="semibold" color="gray-700">
          {label}
        </Text>
        {description && (
          <Text id={`${field.id}-desc`} size="sm" color="gray-600">
            {description}
          </Text>
        )}
        {context.config?.validation && <InlineValidation name={name} />}
      </Stack>
    </div>
  )
}

ToggleField.propTypes = {
  className: PropTypes.string,
  id: PropTypes.string,
  name: PropTypes.string.isRequired,
  description: PropTypes.string,
  label: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func,
}

export default ToggleField
