// Libs
// -----------------------------------------------------------------------------
import React, { FC, useState, useEffect } from 'react';
import { TimePicker, TimePickerProps } from 'antd';
import moment, { Moment } from 'moment';

// Props
// -----------------------------------------------------------------------------
type StringTimePickerProps = TimePickerProps & {
  value?: string;
  onChange?: (value: string) => void;
};

/**
 * Компонент-обертка для Ant TimePicker, принимающий строку формата HH:mm:ss.
 */
export const StringTimePicker: FC<StringTimePickerProps> = ({
  value,
  onChange,
  ...timePickerProps
}) => {
  const [momentValue, setMomentValue] = useState<Moment | null>(null);

  useEffect(() => {
    setMomentValue(value ? moment(value, 'HH:mm:ss') : null);
  }, [value]);

  return (
    <TimePicker
      value={momentValue}
      onChange={(newMomentValue: Moment | null, dateString: string) => {
        setMomentValue(newMomentValue);
        if (onChange) {
          onChange(dateString);
        }
      }}
      {...timePickerProps}
    />
  );
};
