import {
  buildApplicationPreviewSubmitText,
  buildLocalApplicationPreviewMessage,
  normalizeApplicationPreview
} from '../../utils/expenseApplicationPreview.js'
import {
  buildTravelPlanningNudgeMessage,
  buildTravelPlanningSuggestedActions
} from '../../utils/travelApplicationPlanning.js'
import { SESSION_TYPE_APPLICATION } from './travelReimbursementConversationModel.js'
import { useTravelReimbursementStewardFollowupFlow } from './travelReimbursementStewardFollowupFlow.js'
import { AI_APPLICATION_ACTION_SUBMIT } from './useTravelReimbursementApplicationPreviewActions.js'

export function useTravelReimbursementApplicationSubmitConfirm({
  activeSessionType,
  applicationSubmitConfirmDialog,
  buildStewardFieldItems,
  createMessage,
  emitDraftSaved,
  formatStewardMissingFieldList,
  formatStewardOntologyFields,
  linkedRequest,
  messages,
  nextTick,
  persistSessionState,
  reviewActionBusy,
  runApplicationPreviewAction,
  scrollToBottom,
  submitComposer,
  submitting,
  toast
}) {
    function openApplicationSubmitConfirm(message) {
      if (!message) {
        return
      }
      if (message.applicationPreview) {
        const normalizedPreview = normalizeApplicationPreview(message.applicationPreview)
        message.applicationPreview = normalizedPreview
        message.text = buildLocalApplicationPreviewMessage(normalizedPreview)
        if (!normalizedPreview.readyToSubmit) {
          toast(`请先补充：${normalizedPreview.missingFields.join('、')}。`)
          persistSessionState()
          return
        }
      }
      applicationSubmitConfirmDialog.value = {
        open: true,
        message
      }
    }

    function closeApplicationSubmitConfirm() {
      if (reviewActionBusy.value) {
        return
      }
      applicationSubmitConfirmDialog.value = {
        open: false,
        message: null
      }
    }

    function resolveApplicationEditClaimId() {
      if (activeSessionType.value !== SESSION_TYPE_APPLICATION) {
        return ''
      }
      const request = linkedRequest.value || {}
      if (!request.applicationEditMode) {
        return ''
      }
      return String(request.claimId || request.claim_id || '').trim()
    }

    const {
      buildStewardContinuationAfterAction,
      pushStewardContinuationMessage,
      resolveStewardMissingFieldItems
    } = useTravelReimbursementStewardFollowupFlow({
      buildStewardFieldItems,
      createMessage,
      formatStewardMissingFieldList,
      formatStewardOntologyFields,
      messages,
      nextTick,
      persistSessionState,
      scrollToBottom
    })

    async function confirmApplicationSubmit(options = {}) {
      const message = applicationSubmitConfirmDialog.value.message
      if (!message || submitting.value || reviewActionBusy.value) {
        return
      }
      const applicationPreview = message?.applicationPreview && typeof message.applicationPreview === 'object'
        ? normalizeApplicationPreview(message.applicationPreview)
        : null
      const applicationSubmitText = applicationPreview
        ? buildApplicationPreviewSubmitText(applicationPreview)
        : '确认提交'
      const applicationEditClaimId = resolveApplicationEditClaimId()
      applicationSubmitConfirmDialog.value = {
        open: false,
        message: null
      }
      const stewardSubmitContinuation = message?.stewardContinuation || null
      reviewActionBusy.value = true
      try {
        const payload = applicationPreview
          ? await runApplicationPreviewAction(
              AI_APPLICATION_ACTION_SUBMIT,
              message
            )
          : await submitComposer({
              rawText: applicationSubmitText,
              userText: String(options.userText || '').trim() || '确认提交',
              skipUserMessage: Boolean(options.skipUserMessage),
              pendingText: '正在提交费用申请...',
              systemGenerated: true,
              skipScopeGuard: true,
              skipStewardPlan: true,
              stewardContinuation: stewardSubmitContinuation,
              sessionTypeOverride: SESSION_TYPE_APPLICATION,
              feedbackOperationType: 'submit_application',
              extraContext: {
                application_preview: applicationPreview,
                user_input_text: applicationSubmitText,
                ...(applicationEditClaimId
                  ? {
                      application_edit_claim_id: applicationEditClaimId,
                      application_edit_claim_no: String(linkedRequest.value?.claimNo || linkedRequest.value?.id || '').trim(),
                      application_edit_mode: true,
                      draft_claim_id: applicationEditClaimId,
                      selected_claim_id: applicationEditClaimId
                    }
                  : {})
              }
            })
        const draftPayload = payload?.result?.draft_payload || {}
        const claimNo = String(draftPayload.claim_no || '').trim()
        const claimId = String(draftPayload.claim_id || '').trim()
        if (String(payload?.status || '').trim() === 'succeeded' && (claimNo || claimId)) {
          message.applicationSubmitConfirmed = true
          emitDraftSaved({
            claimId,
            claimNo,
            status: 'submitted',
            approvalStage: String(draftPayload.approval_stage || '直属领导审批').trim(),
            documentType: 'application'
          })
          persistSessionState()
        }
        const planningText = buildTravelPlanningNudgeMessage(applicationPreview, draftPayload)
        const planningActions = buildTravelPlanningSuggestedActions(applicationPreview, draftPayload).map((action) => ({
          ...action,
          payload: {
            ...(action.payload || {}),
            applicationPreview,
            draftPayload
          }
        }))
        if (planningText && planningActions.length) {
          messages.value.push(createMessage('assistant', planningText, [], {
            meta: ['行程规划推荐'],
            suggestedActions: planningActions
          }))
          persistSessionState()
          nextTick(scrollToBottom)
        }
        const stewardFollowup = buildStewardContinuationAfterAction(message, '申请单已完成')
        if (stewardFollowup) {
          await pushStewardContinuationMessage(stewardFollowup)
        }
      } catch (error) {
        toast(String(error?.message || '').trim() || '申请提交失败，请稍后重试。')
      } finally {
        reviewActionBusy.value = false
      }
    }



    return {
      closeApplicationSubmitConfirm,
      confirmApplicationSubmit,
      openApplicationSubmitConfirm,
      resolveStewardMissingFieldItems
    }
}
