/**
 * Generates input IDs or names based on the provided attributes, range, and position.
 *
 * @param attribute - A single string or a tuple of two strings representing the attribute names.
 * @param range - A boolean indicating whether the input is part of a range.
 * @param position - Optional. Specifies the position ('start' or 'end') when `range` is true.
 * @returns A string representing the input ID or name.
 */
export const getInputIdOrName = (
  attribute: string | [string, string],
  range: boolean,
  position?: 'start' | 'end',
): string => {
  if (range && !Array.isArray(attribute)) {
    return `${attribute}-${position}-date`
  }

  if (Array.isArray(attribute)) {
    return position === 'start' ? attribute[0] : attribute[1]
  }

  return attribute
}

/**
 * Parses a date string into a Date object based on the provided locale and time inclusion.
 *
 * @param dateString - The date string to parse.
 * @param locale - The locale to use for parsing the date string.
 * @param includeTime - Optional. Determines whether to include time in the parsed Date object.
 * @returns A Date object representing the parsed date and time, or `undefined` if parsing fails.
 */
export const getLocalDateFromString = (
  string: string,
  locale: string,
  time?: boolean,
): Date | undefined => {
  if (!Number.isNaN(Date.parse(string))) {
    return new Date(Date.parse(string))
  }

  const date = new Date(2013, 11, 31, 17, 19, 22)
  let regex = time ? date.toLocaleString(locale) : date.toLocaleDateString(locale)
  regex = regex
    .replace('2013', '(?<year>[0-9]{2,4})')
    .replace('12', '(?<month>[0-9]{1,2})')
    .replace('31', '(?<day>[0-9]{1,2})')

  if (time) {
    regex = regex
      .replace('5', '(?<hour>[0-9]{1,2})')
      .replace('17', '(?<hour>[0-9]{1,2})')
      .replace('19', '(?<minute>[0-9]{1,2})')
      .replace('22', '(?<second>[0-9]{1,2})')
      .replace('PM', '(?<ampm>[A-Z]{2})')
  }

  const rgx = new RegExp(`${regex}`)
  const partials = string.match(rgx)

  if (partials === null) return

  const newDate =
    partials.groups &&
    (time
      ? new Date(
          Number(partials.groups['year']),
          Number(partials.groups['month']) - 1,
          Number(partials.groups['day']),
          partials.groups['ampm']
            ? partials.groups['ampm'] === 'PM'
              ? Number(partials.groups['hour']) + 12
              : Number(partials.groups['hour'])
            : Number(partials.groups['hour']),
          Number(partials.groups['minute']),
          Number(partials.groups['second']),
        )
      : new Date(
          Number(partials.groups['year']),
          Number(partials.groups['month']) - 1,
          Number(partials.groups['day']),
        ))

  return newDate
}
