import { format, parse, parseISO } from 'date-fns'
import {
  useState,
  ChangeEvent,
  DetailedHTMLProps,
  InputHTMLAttributes
} from 'react'

type IDateTime = {
  onChange: GenericEventHandler
  label?: string
  value: string
} & Omit<
  DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>,
  'onChange' | 'value'
>

const DateTimeInput = ({
  name,
  label,
  id,
  type,
  value,
  onChange,
  ...props
}: IDateTime) => {
  const timeFormat = 'HH:mm'
  const dateFormat = 'yyyy-MM-dd'

  const [state, setState] = useState({
    DTILOCALSTATEdate: format(parseISO(value), dateFormat),
    DTILOCALSTATEtime: format(parseISO(value), timeFormat)
  })

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setState({ ...state, [event.target.name]: event.target.value })
  }

  function handleBlur(event: ChangeEvent<HTMLInputElement>) {
    const timeISO = parse(
      `${state.DTILOCALSTATEdate} ${state.DTILOCALSTATEtime}`,
      `${dateFormat} ${timeFormat}`,
      new Date(0)
    )
    const returnEvent = {
      target: {
        name,
        type: 'custom',
        value: timeISO.toISOString()
      }
    }
    onChange(returnEvent)
  }

  return (
    <>
      <input
        type='date'
        id='DTILOCALSTATEdate'
        name='DTILOCALSTATEdate'
        {...props}
        value={state.DTILOCALSTATEdate}
        onChange={handleChange}
        onBlur={handleBlur}
      />
      <input
        type='time'
        id='DTILOCALSTATEtime'
        name='DTILOCALSTATEtime'
        {...props}
        step={60}
        value={state.DTILOCALSTATEtime}
        onChange={handleChange}
        onBlur={handleBlur}
      />
    </>
  )
}

export default DateTimeInput
