import { computed } from 'vue'

export function useTravelReimbursementCreateViewState({
  ASSISTANT_SESSION_MODE_OPTIONS,
  SESSION_TYPE_APPLICATION,
  SESSION_TYPE_APPROVAL,
  SESSION_TYPE_BUDGET,
  SESSION_TYPE_KNOWLEDGE,
  SESSION_TYPE_STEWARD,
  activeSessionType,
  canExposeReviewPanelScope,
  conversationId,
  currentInsight,
  currentUser,
  filterAssistantSessionModes,
  getActiveFlowSteps,
  hasMeaningfulSessionMessages,
  insightPanelCollapsed,
  linkedRequest,
  messages,
  normalizeReviewPanelScope,
  props,
  resolveAssistantSessionMode,
  submitting,
  workbenchVisible
}) {
  const isKnowledgeSession = computed(() => activeSessionType.value === SESSION_TYPE_KNOWLEDGE)
  const isApplicationSession = computed(() => activeSessionType.value === SESSION_TYPE_APPLICATION)
  const isStewardSession = computed(() => activeSessionType.value === SESSION_TYPE_STEWARD)
  const activeAssistantMode = computed(() => resolveAssistantSessionMode(activeSessionType.value))
  const assistantHeaderTitle = computed(() => (isStewardSession.value ? '小财管家' : '个人工作台'))
  const assistantHeaderDescription = computed(() =>
    isStewardSession.value ? '统一财务任务编排入口' : '个人工作窗，一站式费控解决枢纽'
  )
  const hasStewardInitialAutoSubmitPayload = computed(() => (
    isStewardSession.value &&
    props.initialPromptAutoSubmit !== false &&
    (
      Boolean(String(props.initialPrompt || '').trim()) ||
      (Array.isArray(props.initialFiles) && props.initialFiles.length > 0)
    )
  ))
  const showStewardInitialRecognition = computed(() => (
    hasStewardInitialAutoSubmitPayload.value &&
    !messages.value.length &&
    (workbenchVisible.value || submitting.value)
  ))
  const hasScopedReviewPayload = computed(() => {
    const agent = currentInsight.value.agent || null
    if (agent?.reviewPayload && canExposeReviewPanelScope(agent.reviewPanelScope)) {
      return true
    }
    if (currentInsight.value.intent === 'agent' && agent) {
      return false
    }
    return messages.value.some((item) =>
      item.role === 'assistant' && item.reviewPayload && canExposeReviewPanelScope(item.reviewPanelScope)
    )
  })
  const hasQueryInsight = computed(() => Boolean(currentInsight.value.agent?.queryPayload))
  const hasInsightPanelContent = computed(() =>
    isKnowledgeSession.value || hasScopedReviewPayload.value || hasQueryInsight.value || getActiveFlowSteps().length > 0
  )
  const showInsightPanel = computed(() => hasInsightPanelContent.value && !insightPanelCollapsed.value)
  const insightPanelToggleLabel = computed(() =>
    showInsightPanel.value ? '隐藏详细信息' : '展开详细信息'
  )
  const composerPlaceholder = computed(() => {
    if (isStewardSession.value) {
      return '例如：申请7月2日去北京出差，同时报销昨天交通费和6月3日上海出差费用。'
    }
    if (isKnowledgeSession.value) {
      return '例如：差旅住宿标准是什么？发票抬头不一致还能报销吗？'
    }
    if (props.entrySource === 'detail' && linkedRequest.value?.id) {
      return `例如：解释一下 ${linkedRequest.value.id} 的报销风险，或帮我生成处理意见草稿。`
    }
    if (activeSessionType.value === SESSION_TYPE_APPLICATION) {
      return '例如：我想先申请一笔差旅费用，去上海支持项目部署。'
    }
    if (activeSessionType.value === SESSION_TYPE_APPROVAL) {
      return '例如：查一下待我审核的单据，或帮我生成这张单据的审核意见。'
    }
    if (activeSessionType.value === SESSION_TYPE_BUDGET) {
      return '例如：查询市场部 Q1 预算编制情况，重点看差旅、通信、招待费和办公用品。'
    }
    return '例如：查一下近10日报销金额、解释酒店超标风险，或根据附件整理报销核对信息。'
  })
  const currentIntentLabel = computed(() => {
    if (isKnowledgeSession.value && currentInsight.value.intent === 'welcome') {
      return '热门问题'
    }
    const labels = isKnowledgeSession.value
      ? {
          welcome: '热门问题',
          agent: '知识回答'
        }
      : {
          welcome: activeAssistantMode.value?.label || '财务助手',
          agent: '处理中'
        }
    return labels[currentInsight.value.intent] ?? 'AI 处理中'
  })
  const canDeleteCurrentSession = computed(
    () => Boolean(conversationId.value) || hasMeaningfulSessionMessages(messages.value)
  )
  const latestReviewMessage = computed(() =>
    [...messages.value].reverse().find((item) =>
      item.role === 'assistant' && item.reviewPayload && canExposeReviewPanelScope(item.reviewPanelScope)
    ) ?? null
  )
  const activeReviewPanelScope = computed(() => {
    const agent = currentInsight.value.agent || null
    const agentScope = normalizeReviewPanelScope(agent?.reviewPanelScope)
    if (agent?.reviewPayload && agentScope) {
      return agentScope
    }
    if (currentInsight.value.intent === 'agent' && agent) {
      return ''
    }
    return normalizeReviewPanelScope(latestReviewMessage.value?.reviewPanelScope)
  })
  const activeReviewPayload = computed(() => {
    const agent = currentInsight.value.agent || null
    if (agent?.reviewPayload && normalizeReviewPanelScope(agent.reviewPanelScope)) {
      return agent.reviewPayload
    }
    if (currentInsight.value.intent === 'agent' && agent) {
      return null
    }
    return latestReviewMessage.value?.reviewPayload || null
  })
  const shortcuts = computed(() => {
    if (isStewardSession.value) {
      return []
    }
    const accessibleModes = filterAssistantSessionModes(ASSISTANT_SESSION_MODE_OPTIONS, currentUser.value)
      .filter((mode) => mode.key !== SESSION_TYPE_STEWARD)
    const visibleModes = props.entrySource === 'budget'
      ? accessibleModes.filter((mode) => mode.key === SESSION_TYPE_BUDGET)
      : accessibleModes
    return visibleModes.map((mode) => ({
      label: mode.label,
      icon: mode.icon,
      action: 'switch_view',
      targetSessionType: mode.key,
      active: mode.key === activeSessionType.value
    }))
  })

  return {
    activeReviewPanelScope,
    activeReviewPayload,
    assistantHeaderDescription,
    assistantHeaderTitle,
    canDeleteCurrentSession,
    composerPlaceholder,
    currentIntentLabel,
    hasInsightPanelContent,
    insightPanelToggleLabel,
    isApplicationSession,
    isKnowledgeSession,
    isStewardSession,
    latestReviewMessage,
    shortcuts,
    showInsightPanel,
    showStewardInitialRecognition
  }
}
