import { useEffect, useState } from 'react'

import { cn } from '@/lib/utils'

import type { FC, FocusEvent } from 'react'


const pad = (n: number) => n.toString ().padStart (2, '0')


const toDateTimeLocalValue = (d: Date) => {
  const y = d.getFullYear ()
  const m = pad (d.getMonth () + 1)
  const day = pad (d.getDate ())
  const h = pad (d.getHours ())
  const min = pad (d.getMinutes ())
  const s = pad (d.getSeconds ())
  return `${ y }-${ m }-${ day }T${ h }:${ min }:${ s }`
}


type Props = {
    value?:     string
    onChange?:  (isoUTC: string | null) => void
    className?: string
    onBlur?:    (ev: FocusEvent<HTMLInputElement>) => void }


export default (({ value, onChange, className, onBlur }: Props) => {
  const [local, setLocal] = useState ('')

  useEffect (() => {
    setLocal (value ? toDateTimeLocalValue (new Date (value)) : '')
  }, [value])

  return (
      <input
	  className={cn ('border rounded p-2', className)}
	  type="datetime-local"
	  step={1}
	  value={local}
	  onChange={ev => {
	    const v = ev.target.value
	    setLocal (v)
	    onChange?.(v ? (new Date (v)).toISOString () : null)
	  }}
	  onBlur={onBlur}/>)
}) satisfies FC<Props>
