import DateTimePickerGroup from './DateTimePickerGroup';
import { DateTimePickerHelper } from './DateTimePickerHelper';

export interface StringDateTimePickerGroupProps
  extends DateTimePickerHelper<string | undefined | null> {}

/**
 * Date Time picker input that consumes JS Date object and outputs as a date time offset string in ISO format `YYYY-MM-DDTHH:mm:ss.sss±hh:mm`.
 *
 * Default display to the user is in `MM/DD/YYYY HH:mm:ss AM/PM` format.
 */
export default function StringDateTimePickerGroup(
  props: StringDateTimePickerGroupProps
) {
  return <DateTimePickerGroup {...props} convert={convertToISOString} />;
}

function convertToISOString(date: Date): string {
  // Get the offset in minutes
  const offsetMinutes = date.getTimezoneOffset();

  // Calculate the offset in hours and minutes
  const offsetHours = Math.floor(Math.abs(offsetMinutes) / 60);
  const offsetMinutesPart = Math.abs(offsetMinutes) % 60;

  // Format the offset in the required format (+/-hh:mm)
  const offsetString =
    (offsetMinutes >= 0 ? '-' : '+') +
    String(offsetHours).padStart(2, '0') +
    ':' +
    String(offsetMinutesPart).padStart(2, '0');

  // Format the date in the required format using `intl.DateTimeFormat`
  const year = new Intl.DateTimeFormat('en', { year: 'numeric' })
    .format(date)
    .padStart(4, '0');

  const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(
    date
  );

  const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);

  const hour = new Intl.DateTimeFormat('en', {
    hour: '2-digit',
    hourCycle: 'h23',
  }).format(date);

  const minute = new Intl.DateTimeFormat('en', { minute: '2-digit' })
    .format(date)
    .padStart(2, '0');

  const second = new Intl.DateTimeFormat('en', {
    second: '2-digit',
    fractionalSecondDigits: 3,
  })
    .format(date)
    .padStart(6, '0');

  return `${year}-${month}-${day}T${hour}:${minute}:${second}${offsetString}`;
}
