import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useNavigation, navItems } from './useNavigation.js'
import { useRequests } from './useRequests.js'
import { useChat } from './useChat.js'
import { useToast } from './useToast.js'
import { documents } from '../data/requests.js'
import { normalizeRequestForUi } from '../utils/requestViewModel.js'

export function useAppShell() {
  const route = useRoute()
  const router = useRouter()

  const travelCreateMode = ref(false)
  const smartEntryOpen = ref(false)
  const smartEntryContext = ref({ prompt: '', source: 'requests', request: null })
  const smartEntrySessionId = ref(0)

  const { activeView, currentView, setView } = useNavigation()
  const { requests, search, filters, ranges, activeRange, filteredRequests, approveRequest, rejectRequest } =
    useRequests()
  const { messages, draft, uploadedFiles, messageList, activeCase, prompts, sendMessage, handleUpload, openChat, openNewChat } =
    useChat(activeView)
  const { toast } = useToast()

  const docSearch = ref('')
  const customRange = ref({ start: '2024-07-06', end: '2024-07-12' })
  const travelPrompts = ['生成差旅摘要', '识别报销风险', '核对审批链', '提取随附票据', '生成沟通建议']

  const selectedTravelRequest = computed(() => {
    const requestId = String(route.params.requestId || '')

    if (!requestId) {
      return null
    }

    const rawRequest = requests.value.find((item) => String(item.id) === requestId)
    return normalizeRequestForUi(rawRequest)
  })

  const detailMode = computed(() => route.name === 'app-request-detail')

  const topBarView = computed(() => {
    if (detailMode.value) {
      return {
        title: '差旅申请详情',
        desc: '查看申请单、票据、审批意见与风控提示。'
      }
    }

    return currentView.value
  })

  const filteredDocuments = computed(() => {
    const key = docSearch.value.trim().toLowerCase()
    return documents.filter((doc) => !key || `${doc.id}${doc.applicant}${doc.destination}${doc.type}`.toLowerCase().includes(key))
  })

  function handleApprove(request) {
    const message = approveRequest(request)
    toast(message)
  }

  function handleReject(request) {
    const message = rejectRequest(request)
    toast(message)
  }

  function handleNavigate(view) {
    travelCreateMode.value = false
    smartEntryOpen.value = false
    setView(view)
  }

  function handleOpenChat(request) {
    travelCreateMode.value = false
    openChat(request)
  }

  function openTravelCreate() {
    smartEntryOpen.value = true
    travelCreateMode.value = false
    smartEntryContext.value = { prompt: '', source: 'topbar', request: null }
    smartEntrySessionId.value += 1
  }

  function openSmartEntry(payload = {}) {
    smartEntryOpen.value = true
    travelCreateMode.value = false

    smartEntryContext.value = {
      prompt: payload.prompt ?? '',
      source: payload.source ?? 'workbench',
      request: payload.request ?? selectedTravelRequest.value
    }
    smartEntrySessionId.value += 1
  }

  function closeSmartEntry() {
    smartEntryOpen.value = false
  }

  function openRequestDetail(request) {
    router.push({
      name: 'app-request-detail',
      params: { requestId: request.id }
    })
  }

  function closeRequestDetail() {
    router.push({ name: 'app-requests' })
  }

  return {
    activeCase,
    activeRange,
    activeView,
    closeRequestDetail,
    closeSmartEntry,
    currentView,
    customRange,
    detailMode,
    docSearch,
    draft,
    filteredDocuments,
    filteredRequests,
    filters,
    handleApprove,
    handleNavigate,
    handleOpenChat,
    handleReject,
    handleUpload,
    messageList,
    messages,
    navItems,
    openChat,
    openNewChat,
    openRequestDetail,
    openSmartEntry,
    openTravelCreate,
    prompts,
    ranges,
    requests,
    search,
    selectedTravelRequest,
    sendMessage,
    setView,
    smartEntryContext,
    smartEntryOpen,
    smartEntrySessionId,
    toast,
    topBarView,
    travelCreateMode,
    travelPrompts,
    uploadedFiles
  }
}
