function normalizeDateValue(value) {
  return String(value || '').trim()
}

const ISO_DATE_PATTERN = '20\\d{2}-\\d{1,2}-\\d{1,2}'
const DATE_RANGE_PATTERN = `${ISO_DATE_PATTERN}(?:\\s*\\u81f3\\s*${ISO_DATE_PATTERN})?`
const LABELED_DATE_PREFIX_RE = new RegExp(
  `^(?:(?:\\u4e1a\\u52a1)?\\u53d1\\u751f\\u65f6\\u95f4|\\u65e5\\u671f|\\u65f6\\u95f4)\\s*[:\\uFF1A]\\s*${DATE_RANGE_PATTERN}[\\uFF0C,\\u3002\\s]*`,
  'u'
)
const RAW_DATE_PREFIX_RE = new RegExp(`^${DATE_RANGE_PATTERN}[\\uFF0C,\\u3002\\s]*`, 'u')

export function getTodayDateValue(date = new Date()) {
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
    return ''
  }

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function canApplyWorkbenchDateSelection({
  mode = 'single',
  singleDate = '',
  rangeStartDate = '',
  rangeEndDate = ''
} = {}) {
  if (mode === 'range') {
    const startDate = normalizeDateValue(rangeStartDate)
    const endDate = normalizeDateValue(rangeEndDate)
    return Boolean(startDate && endDate && startDate <= endDate)
  }

  return Boolean(normalizeDateValue(singleDate))
}

export function buildWorkbenchDateLabel({
  mode = 'single',
  singleDate = '',
  rangeStartDate = '',
  rangeEndDate = ''
} = {}) {
  if (!canApplyWorkbenchDateSelection({ mode, singleDate, rangeStartDate, rangeEndDate })) {
    return ''
  }

  if (mode !== 'range') {
    return normalizeDateValue(singleDate)
  }

  const startDate = normalizeDateValue(rangeStartDate)
  const endDate = normalizeDateValue(rangeEndDate)
  return startDate === endDate ? startDate : `${startDate} \u81f3 ${endDate}`
}

export function stripWorkbenchDateLabelFromDraft(rawDraft) {
  return String(rawDraft || '')
    .replace(LABELED_DATE_PREFIX_RE, '')
    .replace(RAW_DATE_PREFIX_RE, '')
    .trim()
}

export function mergeWorkbenchDateLabelIntoDraft(rawDraft, dateLabel) {
  const label = String(dateLabel || '').trim()
  if (!label) {
    return String(rawDraft || '').trim()
  }

  const draft = stripWorkbenchDateLabelFromDraft(rawDraft)

  return draft ? `${label}\uFF0C${draft}` : label
}
