import { ref } from 'vue'

import {
  APPLICATION_TRANSPORT_MODE_OPTIONS,
  buildApplicationPreviewRows,
  buildLocalApplicationPreviewMessage,
  normalizeApplicationPreview
} from '../../utils/expenseApplicationPreview.js'

export function useApplicationPreviewEditor({ persistSessionState, toast } = {}) {
  const applicationPreviewEditor = ref({
    messageId: '',
    fieldKey: '',
    draftValue: ''
  })

  function resolveApplicationPreviewRows(message) {
    return buildApplicationPreviewRows(message?.applicationPreview || {})
  }

  function resolveApplicationPreviewEditorControl(fieldKey) {
    return fieldKey === 'transportMode' ? 'select' : 'text'
  }

  function resolveApplicationPreviewEditorOptions(fieldKey) {
    return fieldKey === 'transportMode' ? APPLICATION_TRANSPORT_MODE_OPTIONS : []
  }

  function isApplicationPreviewEditing(message, fieldKey) {
    return (
      String(applicationPreviewEditor.value.messageId || '') === String(message?.id || '') &&
      applicationPreviewEditor.value.fieldKey === fieldKey
    )
  }

  function openApplicationPreviewEditor(message, fieldKey, value) {
    if (!message?.applicationPreview || !fieldKey) return
    const targetRow = buildApplicationPreviewRows(message.applicationPreview)
      .find((row) => row.key === fieldKey)
    if (targetRow && targetRow.editable === false) return
    const normalizedValue = String(value || '').trim() === '待补充' ? '' : String(value || '')
    applicationPreviewEditor.value = {
      messageId: String(message.id || ''),
      fieldKey,
      draftValue: fieldKey === 'transportMode' && !APPLICATION_TRANSPORT_MODE_OPTIONS.includes(normalizedValue)
        ? ''
        : normalizedValue
    }
  }

  function cancelApplicationPreviewEditor() {
    applicationPreviewEditor.value = {
      messageId: '',
      fieldKey: '',
      draftValue: ''
    }
  }

  function commitApplicationPreviewEditor(message) {
    const editor = applicationPreviewEditor.value
    if (!message?.applicationPreview || String(editor.messageId || '') !== String(message.id || '') || !editor.fieldKey) {
      cancelApplicationPreviewEditor()
      return false
    }

    const nextValue = String(editor.draftValue || '').trim()
    const nextPreview = normalizeApplicationPreview({
      ...message.applicationPreview,
      fields: {
        ...(message.applicationPreview.fields || {}),
        [editor.fieldKey]: nextValue
      }
    })
    message.applicationPreview = nextPreview
    message.text = buildLocalApplicationPreviewMessage(nextPreview)
    cancelApplicationPreviewEditor()
    persistSessionState?.()
    toast?.('已更新核对表内容。')
    return true
  }

  function handleApplicationPreviewEditorKeydown(event, message) {
    if (event.key === 'Enter') {
      event.preventDefault()
      commitApplicationPreviewEditor(message)
      return
    }
    if (event.key === 'Escape') {
      event.preventDefault()
      cancelApplicationPreviewEditor()
    }
  }

  return {
    applicationPreviewEditor,
    resolveApplicationPreviewRows,
    resolveApplicationPreviewEditorControl,
    resolveApplicationPreviewEditorOptions,
    isApplicationPreviewEditing,
    openApplicationPreviewEditor,
    commitApplicationPreviewEditor,
    cancelApplicationPreviewEditor,
    handleApplicationPreviewEditorKeydown
  }
}
