import { ref } from 'vue'

import { showError, showSuccess } from '@/lib/feedback'
import { fetchAdminCloudtentaclesSkuList } from '@/services/admin'
import type { AdminCloudtentaclesSkuItem } from '@/types/admin'

import type { EditableItem } from './types'

export function useKuaishouCloudSku(cloudtentaclesSourceOptions?: { value: { key: string }[] }) {
  const cloudSkuCatalogLoadingBySourceKey = ref<Record<string, boolean>>({})
  const cloudSkuCatalogErrorMessage = ref('')
  const cloudSkuCatalogBySourceKey = ref<Record<string, AdminCloudtentaclesSkuItem[]>>({})

  function getSourceKey(item: EditableItem) {
    return String(item.cloudSourceKey || 'default').trim()
  }

  async function ensureCloudSkuCatalogLoaded(item: EditableItem, force = false) {
    const sourceKey = getSourceKey(item)
    if (!force && (cloudSkuCatalogBySourceKey.value[sourceKey]?.length ?? 0) > 0) {
      return cloudSkuCatalogBySourceKey.value[sourceKey]
    }

    cloudSkuCatalogLoadingBySourceKey.value[sourceKey] = true
    cloudSkuCatalogErrorMessage.value = ''

    try {
      const response = await fetchAdminCloudtentaclesSkuList({ sourceKey })
      cloudSkuCatalogBySourceKey.value[sourceKey] = Array.isArray(response.data.items)
        ? response.data.items
        : []
      return cloudSkuCatalogBySourceKey.value[sourceKey]
    } catch (error) {
      cloudSkuCatalogBySourceKey.value[sourceKey] = []
      cloudSkuCatalogErrorMessage.value =
        error instanceof Error ? error.message : 'cloud SKU 列表查询失败'
      throw error
    } finally {
      cloudSkuCatalogLoadingBySourceKey.value[sourceKey] = false
    }
  }

  function getCloudSkuKeyword(item: EditableItem) {
    return (
      [item.internalSkuCode, item.internalSkuName, item.resolvedSkuName, item.externalSkuName]
        .map((value) => String(value || '').trim())
        .find(Boolean) || ''
    )
  }

  function normalizeSearchText(value: string) {
    return String(value || '')
      .trim()
      .toLowerCase()
  }

  function scoreCloudSkuMatch(item: AdminCloudtentaclesSkuItem, keyword: string) {
    const normalizedKeyword = normalizeSearchText(keyword)
    if (!normalizedKeyword) {
      return 0
    }

    const name = normalizeSearchText(item.name)
    const description = normalizeSearchText(item.description)

    if (name === normalizedKeyword) {
      return 120
    }

    if (name.startsWith(normalizedKeyword)) {
      return 100
    }

    if (name.includes(normalizedKeyword)) {
      return 80
    }

    if (description.includes(normalizedKeyword)) {
      return 40
    }

    return 0
  }

  function getCloudSkuOptions(item: EditableItem) {
    const sourceKey = getSourceKey(item)
    const catalog = cloudSkuCatalogBySourceKey.value[sourceKey] || []
    const keyword = getCloudSkuKeyword(item)
    const scored = catalog
      .map((sku) => ({ sku, score: scoreCloudSkuMatch(sku, keyword) }))
      .filter((entry) => entry.score > 0 || entry.sku.id === Number(item.cloudSkuId || 0))
      .sort((left, right) => {
        if (right.score !== left.score) {
          return right.score - left.score
        }

        return left.sku.name.localeCompare(right.sku.name, 'zh-CN')
      })
      .map((entry) => entry.sku)

    if (scored.length > 0) {
      return scored.slice(0, 80)
    }

    return catalog.slice(0, 80)
  }

  function formatCloudSkuOptionLabel(item: AdminCloudtentaclesSkuItem) {
    const price = Number(item.price || 0)
    const inventory = Number(item.inventory || 0)
    return `${item.name} · ID ${item.id} · 库存 ${inventory} · 价格 ${price}`
  }

  function handleCloudSkuSelected(item: EditableItem, value: number | string | undefined) {
    const skuId = Number(value || 0)
    item.cloudSkuId = Number.isInteger(skuId) && skuId > 0 ? skuId : 0

    if (!item.cloudSkuId) {
      item.cloudSkuName = ''
      return
    }

    const sourceKey = getSourceKey(item)
    const catalog = cloudSkuCatalogBySourceKey.value[sourceKey] || []
    const matched = catalog.find((sku) => sku.id === item.cloudSkuId)
    item.cloudSkuName = matched?.name || item.cloudSkuName || ''
  }

  async function handleCloudSkuDropdownVisible(item: EditableItem, visible: boolean) {
    if (!visible) {
      return
    }

    try {
      await ensureCloudSkuCatalogLoaded(item)
      if (item.cloudSkuId && !item.cloudSkuName) {
        handleCloudSkuSelected(item, item.cloudSkuId)
      }
    } catch (error) {
      showError(error instanceof Error ? error.message : 'cloud SKU 列表查询失败')
    }
  }

  async function refreshCloudSkuCatalog(item?: EditableItem) {
    try {
      if (item) {
        await ensureCloudSkuCatalogLoaded(item, true)
        const sourceKey = getSourceKey(item)
        const count = cloudSkuCatalogBySourceKey.value[sourceKey]?.length ?? 0
        showSuccess(`cloud SKU 列表（${sourceKey}）已刷新，共 ${count} 条`)
      } else {
        // No item provided — refresh all configured sourceKeys, or at least 'default'
        const cachedKeys = Object.keys(cloudSkuCatalogBySourceKey.value)
        const configuredKeys = cloudtentaclesSourceOptions?.value?.map((s) => s.key) || []
        const keysToRefresh =
          cachedKeys.length > 0
            ? cachedKeys
            : configuredKeys.length > 0
            ? configuredKeys
            : ['default']

        for (const key of keysToRefresh) {
          await ensureCloudSkuCatalogLoaded(
            { cloudSourceKey: key, localId: '' } as EditableItem,
            true,
          )
        }
        const total = Object.values(cloudSkuCatalogBySourceKey.value).reduce(
          (sum, list) => sum + list.length,
          0,
        )
        showSuccess(`cloud SKU 列表已全部刷新，共 ${total} 条`)
      }
    } catch (error) {
      showError(error instanceof Error ? error.message : 'cloud SKU 列表查询失败')
    }
  }

  const cloudSkuCatalogLoading = ref(false)
  // Maintain backward-compat: derive a combined loading state
  // The template uses cloudSkuCatalogLoading for the refresh button spinner
  function syncCloudSkuCatalogLoading() {
    cloudSkuCatalogLoading.value = Object.values(cloudSkuCatalogLoadingBySourceKey.value).some(
      Boolean,
    )
  }

  return {
    cloudSkuCatalogLoading,
    cloudSkuCatalogLoadingBySourceKey,
    cloudSkuCatalogErrorMessage,
    cloudSkuCatalogBySourceKey,
    getCloudSkuOptions,
    formatCloudSkuOptionLabel,
    handleCloudSkuSelected,
    handleCloudSkuDropdownVisible,
    refreshCloudSkuCatalog,
    syncCloudSkuCatalogLoading,
  }
}
