import { Moment } from 'moment'
import { TimePicker, TimePickerProps } from 'antd'
import { memo, useCallback, useMemo } from 'react'

import { defaultTimeFormat, momentToTimeOnly, timeOnlyToMoment } from '@utils/datetime'
import { TimeOnly } from '@api'

export type TimePickerWrapperProps = Omit<Omit<TimePickerProps, 'value'>, 'onChange'> & {
    value?: TimeOnly,
    onChange?: (date: TimeOnly | null) => any
    isUTC?: boolean
}

export const TimePickerWrapper = memo<TimePickerWrapperProps>(({ value, onChange, isUTC, ...other }) => {
    const time = useMemo(() => value ? timeOnlyToMoment(value, isUTC) : null, [value, isUTC])

    const onTimeChange = useCallback((time: Moment | null) => onChange?.(time ? momentToTimeOnly(time) : null), [onChange])

    return (
        <TimePicker
            allowClear={false}
            format={defaultTimeFormat}
            defaultValue={timeOnlyToMoment()}
            onChange={onTimeChange}
            value={time}
            {...other}
        />
    )
})

export default TimePickerWrapper
