import { watch } from 'vue'

function isApplicationPreviewDateField(fieldKey = '') {
  return ['time', 'time_return'].includes(String(fieldKey || '').trim())
}

export function useTravelReimbursementApplicationPreviewDateEditor({
  applicationPreviewEditor,
  cancelApplicationPreviewEditor,
  commitApplicationPreviewDateEditor,
  composerDateMode,
  composerDatePickerOpen,
  composerRangeEndDate,
  composerRangeStartDate,
  composerSingleDate,
  formatDateInputValue,
  isApplicationPreviewEditing,
  messages,
  openApplicationPreviewEditor,
  travelCalculatorOpen
}) {
  function applyLinkedApplicationPreviewDateSelection(selection) {
    const editor = applicationPreviewEditor.value
    if (!isApplicationPreviewDateField(editor.fieldKey) || !editor.messageId) {
      return false
    }

    const targetMessage = messages.value.find((item) =>
      String(item.id || '') === String(editor.messageId || '')
    )
    if (!targetMessage?.applicationPreview) {
      return false
    }

    applicationPreviewEditor.value = {
      ...editor,
      dateMode: selection.mode === 'range' ? 'range' : 'single',
      singleDate: selection.startDate,
      rangeStartDate: selection.startDate,
      rangeEndDate: selection.endDate || selection.startDate
    }
    return commitApplicationPreviewDateEditor(targetMessage)
  }

  function syncComposerDateFromApplicationEditor() {
    const editor = applicationPreviewEditor.value
    const today = formatDateInputValue()
    composerDateMode.value = editor.dateMode === 'range' ? 'range' : 'single'
    composerSingleDate.value = editor.singleDate || today
    composerRangeStartDate.value = editor.rangeStartDate || composerSingleDate.value || today
    composerRangeEndDate.value = editor.rangeEndDate || composerRangeStartDate.value || today
    composerDatePickerOpen.value = true
    travelCalculatorOpen.value = false
  }

  function openApplicationPreviewEditorFromUi(message, fieldKey, value) {
    openApplicationPreviewEditor(message, fieldKey, value)
    if (isApplicationPreviewDateField(fieldKey) && isApplicationPreviewEditing(message, fieldKey)) {
      syncComposerDateFromApplicationEditor()
    }
  }

  watch(composerDatePickerOpen, (open, previousOpen) => {
    if (!open && previousOpen && isApplicationPreviewDateField(applicationPreviewEditor.value.fieldKey)) {
      cancelApplicationPreviewEditor()
    }
  })

  return {
    applyLinkedApplicationPreviewDateSelection,
    openApplicationPreviewEditorFromUi
  }
}
