import { useField } from 'formik';
import { DateTime } from 'luxon';
import React from 'react';
import { useFormikError } from '../useFormikError';
import { DateTimeText, DateTimeTextProps } from './DateTimeText';
/**
 * This component should be used to render a DateTimeTextField inside a Formik form.
 *
 * @example
 * <Field name="title" label="Title" as={DateTimeTextField} />
 */
export const DateTimeTextField: React.FC<
  Omit<DateTimeTextProps, 'error' | 'onChange'>
> = (props) => {
  const error = useFormikError(props.name);
  const [, meta, helpers] = useField(props.name);

  const handleChange = (value: string | null, valid: boolean): void => {
    if (!valid) {
      helpers.setError('Invalid Date');
      helpers.setValue(value, false);
    } else {
      const initialDateTime = DateTime.fromISO(meta.initialValue);
      const newDateTime = DateTime.fromISO(value ?? '');

      if (newDateTime.setZone(initialDateTime.zone).equals(initialDateTime)) {
        // If the new date is the same as the initial value and the timezone is the only change,
        // set it to the initial value
        helpers.setValue(meta.initialValue);
      } else if (
        (value === null || value === '') &&
        (!meta.initialValue || meta.initialValue === '')
      ) {
        // If the value is null or empty and the initial value is also null or empty,
        // set it to the initial value
        helpers.setValue(meta.initialValue);
      } else {
        helpers.setValue(value);
      }
    }
  };

  return <DateTimeText {...props} error={error} onChange={handleChange} />;
};
