import { computed, reactive, ref } from 'vue'

import { showSuccess } from '@/lib/feedback'
import { fetchAdminNinetyoneOrders } from '@/services/admin'
import type { AdminNinetyoneOrderItem } from '@/types/admin'

import type { EditableItem } from './types'

import type { useKuaishouCloudConfig } from './useKuaishouCloudConfig'

export function useKuaishouCloudNinetyone(
  config: ReturnType<typeof useKuaishouCloudConfig>,
) {
  const ninetyoneLookupLoading = ref(false)
  const ninetyoneLookupErrorMessage = ref('')
  const ninetyoneLookupResults = ref<AdminNinetyoneOrderItem[]>([])
  const importedNinetyoneOrderKeys = ref<string[]>([])
  const ninetyoneLookupForm = reactive({
    status: 'pending_config' as 'pending_config' | 'all' | 'manual_failed',
    page: 1,
    pageSize: 20,
  })

  const ninetyoneLookupMetrics = computed(() => {
    const importedCount = ninetyoneLookupResults.value.filter((item) =>
      isNinetyoneProductImported(item),
    ).length
    const pendingCount = ninetyoneLookupResults.value.filter(
      (item) => item.orderStatus === 'pending_config',
    ).length
    return {
      total: ninetyoneLookupResults.value.length,
      importedCount,
      availableCount: Math.max(ninetyoneLookupResults.value.length - importedCount, 0),
      pendingCount,
    }
  })

  function createItemFromNinetyoneOrder(item: AdminNinetyoneOrderItem): EditableItem {
    const productNo = String(item.productNo || '').trim()
    const productName = String(item.productName || productNo).trim()
    const defaultShop = config.getDefaultKuaishouConsumeShop()
    const shopOpts = config.getKuaishouConsumeShopOptions()
    const shop = defaultShop || (shopOpts.length > 0 ? shopOpts[0] : null)
    return {
      localId: crypto.randomUUID(),
      id: '',
      enabled: true,
      priority: 100,
      provider: '91kaquan',
      platform: 'kuaishou',
      shopId: item.shopId || '91kaquan',
      internalSkuCode: '',
      internalSkuName: productName,
      externalSkuCode: productNo,
      externalItemId: productNo,
      externalSkuName: productName,
      resolvedSkuName: productName,
      cloudSourceKey: 'default',
      cloudSkuId: 0,
      cloudSkuName: '',
      vnKey: '1',
      autoBuyEnabled: true,
      minAssetReserve: 0,
      autoReturnNumberAfterDispatch: false,
      autoConsumeAfterDispatch: false,
      kuaishouConsumeShopId: shop?.shopId || '',
      kuaishouConsumeShopName: shop?.kshopName || '',
      notes: `从 91卡券订单 ${item.orderNo} 导入`,
    }
  }

  function findExistingItemFromNinetyoneOrder(order: AdminNinetyoneOrderItem) {
    const productNo = String(order.productNo || '').trim()
    const productName = String(order.productName || '').trim()
    const shopId = String(order.shopId || '91kaquan').trim()

    return (
      config.items.value.find((item) => {
        const sameSource = item.provider.trim() === '91kaquan' && item.platform.trim() === 'kuaishou'
        const sameShop = !shopId || item.shopId.trim() === shopId
        const sameProductNo =
          productNo &&
          (item.externalSkuCode.trim() === productNo || item.externalItemId.trim() === productNo)
        const sameName =
          productName &&
          [item.externalSkuName, item.internalSkuName, item.resolvedSkuName].some(
            (value) => value.trim() === productName,
          )
        return sameSource && sameShop && (sameProductNo || sameName)
      }) || null
    )
  }

  async function importNinetyoneProduct(item: AdminNinetyoneOrderItem) {
    config.validationState.value = null
    const importKey = getNinetyoneOrderImportKey(item)
    const existing = findExistingItemFromNinetyoneOrder(item)
    if (existing) {
      config.setCollapsed(existing.localId, false)
      if (!importedNinetyoneOrderKeys.value.includes(importKey)) {
        importedNinetyoneOrderKeys.value = [...importedNinetyoneOrderKeys.value, importKey]
      }
      showSuccess('已定位到现有 91卡券规则草稿，直接继续完善即可')
      await config.focusValidationTarget(existing.localId)
      return
    }

    const next = createItemFromNinetyoneOrder(item)
    config.items.value.unshift(next)
    config.setCollapsed(next.localId, false)

    if (!importedNinetyoneOrderKeys.value.includes(importKey)) {
      importedNinetyoneOrderKeys.value = [...importedNinetyoneOrderKeys.value, importKey]
    }

    await config.focusValidationTarget(next.localId)
  }

  function getNinetyoneOrderImportKey(item: AdminNinetyoneOrderItem) {
    return [item.orderNo, item.productNo, item.shopId || '91kaquan']
      .map((value) => String(value || '').trim())
      .join(':')
  }

  function isNinetyoneProductImported(item: AdminNinetyoneOrderItem) {
    return importedNinetyoneOrderKeys.value.includes(getNinetyoneOrderImportKey(item))
  }

  async function lookupNinetyoneProducts() {
    ninetyoneLookupLoading.value = true
    ninetyoneLookupErrorMessage.value = ''

    try {
      const response = await fetchAdminNinetyoneOrders({
        page: Number(ninetyoneLookupForm.page || 1),
        pageSize: Number(ninetyoneLookupForm.pageSize || 20),
        status: ninetyoneLookupForm.status,
      })
      ninetyoneLookupResults.value = response.data.items
      importedNinetyoneOrderKeys.value = []
    } catch (error) {
      ninetyoneLookupResults.value = []
      ninetyoneLookupErrorMessage.value =
        error instanceof Error ? error.message : '91卡券订单查询失败'
    } finally {
      ninetyoneLookupLoading.value = false
    }
  }

  return {
    ninetyoneLookupLoading,
    ninetyoneLookupErrorMessage,
    ninetyoneLookupResults,
    importedNinetyoneOrderKeys,
    ninetyoneLookupForm,
    ninetyoneLookupMetrics,
    importNinetyoneProduct,
    isNinetyoneProductImported,
    lookupNinetyoneProducts,
  }
}
