import { computed, ref } from 'vue'

import { showError, showSuccess } from '@/lib/feedback'
import { saveAdminAgisoShopConfigs } from '@/services/admin'
import type {
  AdminAgisoMessagingDefaults,
  AdminAgisoObservedShopItem,
  AdminAgisoShopConfigItem,
} from '@/types/admin'

import type { EditableDefaults, EditableShop } from './types'

export function useAdminAgisoPlatform() {
  const saving = ref(false)
  const agisoFilePath = ref('')
  const defaults = ref<EditableDefaults>(createEmptyDefaults())
  const shops = ref<EditableShop[]>([])
  const observedShops = ref<AdminAgisoObservedShopItem[]>([])
  const expandedShopIds = ref<string[]>([])

  const agisoStats = computed(() => ({
    configuredShopCount: shops.value.length,
    observedShopCount: observedShops.value.length,
    pendingObservedCount: observedShops.value.filter((item) => !item.configured).length,
  }))

  function hydrateAgisoConfig(data: {
    filePath: string
    defaults: AdminAgisoMessagingDefaults
    shops: AdminAgisoShopConfigItem[]
    observedShops: AdminAgisoObservedShopItem[]
  }) {
    agisoFilePath.value = data.filePath
    defaults.value = mapEditableDefaults(data.defaults)
    shops.value = data.shops.map(mapEditableShop)
    observedShops.value = data.observedShops
    expandedShopIds.value = []
  }

  function addShop() {
    const shop = createEmptyShop()
    shops.value.unshift(shop)
    expandShop(shop.id)
  }

  function removeShop(id: string) {
    shops.value = shops.value.filter((item) => item.id !== id)
    collapseShop(id)
  }

  function importObservedShop(item: AdminAgisoObservedShopItem) {
    const shop: EditableShop = {
      id: crypto.randomUUID(),
      shopId: item.shopId,
      shopName: item.detectedShopName || item.displayShopName || '',
      accessToken: '',
      enabled: true,
      messageTemplate: '',
      autoDeliveryMessageTemplate: '',
    }
    shops.value.unshift(shop)
    expandShop(shop.id)
  }

  function isShopExpanded(id: string) {
    return expandedShopIds.value.includes(id)
  }

  function expandShop(id: string) {
    if (expandedShopIds.value.includes(id)) {
      return
    }
    expandedShopIds.value = [id, ...expandedShopIds.value]
  }

  function collapseShop(id: string) {
    expandedShopIds.value = expandedShopIds.value.filter((item) => item !== id)
  }

  function toggleShop(id: string) {
    if (isShopExpanded(id)) {
      collapseShop(id)
      return
    }
    expandShop(id)
  }

  function expandAllShops() {
    expandedShopIds.value = shops.value.map((item) => item.id)
  }

  function collapseAllShops() {
    expandedShopIds.value = []
  }

  function describeShop(shop: EditableShop) {
    const overrides: string[] = []

    if (shop.messageTemplate.trim()) {
      overrides.push('领取模板')
    }
    if (shop.autoDeliveryMessageTemplate.trim()) {
      overrides.push('发货模板')
    }

    return overrides.length === 0 ? '使用默认模板' : `已覆盖 ${overrides.join('、')}`
  }

  async function saveAgisoConfigs(reloadConfigs: () => Promise<void>) {
    const payloadDefaults = {
      messageTemplate: defaults.value.messageTemplate.trim(),
      autoDeliveryMessageTemplate: defaults.value.autoDeliveryMessageTemplate.trim(),
    }
    const payload = shops.value
      .map((item) => ({
        shopId: item.shopId.trim(),
        shopName: item.shopName.trim(),
        accessToken: item.accessToken.trim(),
        enabled: item.enabled,
        messageTemplate: item.messageTemplate.trim(),
        autoDeliveryMessageTemplate: item.autoDeliveryMessageTemplate.trim(),
      }))
      .filter((item) => item.shopId && item.accessToken)

    saving.value = true

    try {
      const response = await saveAdminAgisoShopConfigs({
        defaults: payloadDefaults,
        shops: payload,
      })
      agisoFilePath.value = response.data.filePath
      defaults.value = mapEditableDefaults(response.data.defaults)
      shops.value = response.data.shops.map(mapEditableShop)
      showSuccess('Agiso 配置已保存')
      await reloadConfigs()
    } catch (error) {
      showError(error instanceof Error ? error.message : '保存 Agiso 配置失败')
    } finally {
      saving.value = false
    }
  }

  return {
    saving,
    agisoFilePath,
    defaults,
    shops,
    observedShops,
    expandedShopIds,
    agisoStats,
    hydrateAgisoConfig,
    addShop,
    removeShop,
    importObservedShop,
    isShopExpanded,
    expandShop,
    collapseShop,
    toggleShop,
    expandAllShops,
    collapseAllShops,
    describeShop,
    saveAgisoConfigs,
  }
}

function createEmptyDefaults(): EditableDefaults {
  return {
    messageTemplate: '',
    autoDeliveryMessageTemplate: '',
  }
}

function createEmptyShop(): EditableShop {
  return {
    id: crypto.randomUUID(),
    shopId: '',
    shopName: '',
    accessToken: '',
    enabled: true,
    messageTemplate: '',
    autoDeliveryMessageTemplate: '',
  }
}

function mapEditableDefaults(item?: AdminAgisoMessagingDefaults): EditableDefaults {
  return {
    messageTemplate: item?.messageTemplate ?? '',
    autoDeliveryMessageTemplate: item?.autoDeliveryMessageTemplate ?? '',
  }
}

function mapEditableShop(item: AdminAgisoShopConfigItem): EditableShop {
  return {
    id: crypto.randomUUID(),
    shopId: item.shopId,
    shopName: item.shopName,
    accessToken: item.AccessToken,
    enabled: item.enabled !== false,
    messageTemplate: item.messageTemplate,
    autoDeliveryMessageTemplate: item.autoDeliveryMessageTemplate,
  }
}
