import React from 'react';
import { toDateTimeString } from '@tamanu/utils/dateTime';
import { set as dateFnsSet, parse, isValid } from 'date-fns';
import { useDateTime } from '@tamanu/ui-components';
import { TimeInput } from '../../Field';

/**
 * A field for selecting a time while keeping the date fixed.
 * The resulting date-time will match the provided `date` (YYYY-MM-DD string) with the time set by the user.
 */
export const TimeWithFixedDateField = ({ field, date, ...props }) => {
  const { toFacilityDateTime, toStoredDateTime, getFacilityNowDate } = useDateTime();

  const displayValue = toFacilityDateTime(field.value);

  const handleChange = event => {
    if (!event.target.value || !date) {
      field.onChange({ target: { value: null, name: field.name } });
      return;
    }
    const [year, month, day] = date.split('-').map(Number);
    const timeDate = parse(event.target.value, 'HH:mm:ss', getFacilityNowDate() ?? new Date());
    if (!isValid(timeDate)) return;
    const facilityDateTime = toDateTimeString(
      dateFnsSet(timeDate, {
        year,
        date: day,
        month: month - 1,
      }),
    );
    const outputValue = toStoredDateTime(facilityDateTime);
    field.onChange({ target: { value: outputValue, name: field.name } });
  };

  return (
    <TimeInput
      name={field.name}
      value={displayValue}
      {...props}
      onChange={handleChange}
      data-testid="timeinput-vbul"
    />
  );
};
