import React from "react"
import PropTypes from "prop-types"
import DatePicker from "react-datepicker"
import "react-datepicker/dist/react-datepicker.css"
import Stack from "../stack"
import Label from "../label"
import { useField } from "../../hooks/use-form"
import Input from "../input"
function DateField({ id, name, label, value, onChange }) {
  const field = useField({ id, name, value, onChange })

  const handleChange = (date) => {
    field.onChange({ target: { name, value: date?.toISOString() } })
  }

  const date = field.value ? new Date(field.value) : null

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

  return (
    <Stack spacing={2} className="design-date-field">
      <Label htmlFor={field.id}>{label}</Label>
      <DatePicker
        id={id}
        onBlur={field.onBlur}
        showPopperArrow={false}
        dateFormat="MMMM d, yyyy"
        selected={date}
        onChange={handleChange}
        customInput={<Input state={state} />}
      />
    </Stack>
  )
}

DateField.propTypes = {
  id: PropTypes.string,
  name: PropTypes.string,
  label: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func,
}

export default DateField
