import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useBasketStore } from '@/stores/basket'
import type { BasketItem } from '@/types/basket'
import type {
  ResearchImportDialogPayload,
  ResearchImportResult,
} from '@/types/research-import'

function normalizeImportItems(
  items: BasketItem[],
  payload: ResearchImportDialogPayload,
): BasketItem[] {
  return items.map((item) => ({
    ...item,
    importance: payload.importance,
    note: payload.note?.trim() || item.note,
    added_at: item.added_at || Date.now(),
  }))
}

export function useResearchImport() {
  const router = useRouter()
  const basketStore = useBasketStore()

  function applyImport(
    items: BasketItem[],
    payload: ResearchImportDialogPayload,
  ): ResearchImportResult {
    const normalizedItems = normalizeImportItems(items, payload)

    let basketAdded = 0
    normalizedItems.forEach((item) => {
      if (basketStore.addItem(item)) {
        basketAdded += 1
      }
    })

    let researchAdded = 0
    if (payload.target === 'new') {
      // Store items in sessionStorage for ResearchCreateView to consume
      sessionStorage.setItem('research-import-items', JSON.stringify(normalizedItems))
      researchAdded = normalizedItems.length
      router.push('/research/new')
    }

    if (payload.target === 'basket') {
      if (basketAdded > 0) {
        message.success(`已加入资料篮 ${basketAdded} 项资料`)
      } else {
        message.warning('所选资料已存在于资料篮中')
      }
    } else {
      if (researchAdded > 0) {
        message.success(`已选择 ${researchAdded} 项资料，正在跳转到新建研究`)
      } else {
        message.info('正在跳转到新建研究')
      }
    }

    return {
      basketAdded,
      researchAdded,
      importedItems: normalizedItems,
    }
  }

  return { applyImport }
}
