import { ref, computed } from 'vue'
import { showError, showSuccess } from '@/lib/feedback'
import {
  consumeAdminKuaishouEticket,
  queryAdminKuaishouEticketDetail,
  queryAdminKuaishouEticketShopInfo,
  saveAdminKuaishouEticketSourceConfig,
} from '@/services/admin'
import type {
  AdminKuaishouEticketConsumeResult,
  AdminKuaishouEticketDetailResult,
  AdminKuaishouEticketShopInfoResult,
  AdminKuaishouEticketSourceConfig,
} from '@/types/admin'
import type { EditableKuaishouEticketShop } from './types'
import { useKuaishouEticketShopManager } from './useKuaishouEticketShopManager'

type KuaishouEticketForm = {
  baseUrl: string
  selectedShopId: string
  queryTicketCode: string
  eTicketId: string
  oid: string
  formToken: string
  num: number
  storeId: string
}

export function useAdminKuaishouEticketPlatform() {
  const shopManager = useKuaishouEticketShopManager()

  const kuaishouEticketFilePath = ref('')
  const kuaishouEticketForm = ref<KuaishouEticketForm>({
    baseUrl: 'https://s.kwaixiaodian.com',
    selectedShopId: '',
    queryTicketCode: '',
    eTicketId: '',
    oid: '',
    formToken: '',
    num: 1,
    storeId: '0',
  })
  const kuaishouEticketSaving = ref(false)
  const kuaishouEticketResolvingShopId = ref('')
  const kuaishouEticketDetailing = ref(false)
  const kuaishouEticketConsuming = ref(false)
  const kuaishouEticketResultError = ref('')
  const kuaishouEticketShopInfoResult = ref<AdminKuaishouEticketShopInfoResult | null>(null)
  const kuaishouEticketDetailResult = ref<AdminKuaishouEticketDetailResult | null>(null)
  const kuaishouEticketConsumeResult = ref<AdminKuaishouEticketConsumeResult | null>(null)

  const activeKuaishouEticketShop = computed(
    () =>
      shopManager.kuaishouEticketShops.value.find(
        (item) => item.id === kuaishouEticketForm.value.selectedShopId,
      ) || null,
  )

  const kuaishouEticketStats = computed(() => ({
    configuredShopCount: shopManager.kuaishouEticketShops.value.length,
    cookieReadyCount: shopManager.kuaishouEticketShops.value.filter((item) => item.cookie.trim()).length,
    selectedShopReady: Boolean(activeKuaishouEticketShop.value?.cookie.trim()),
    detailReady: Boolean(kuaishouEticketDetailResult.value?.detail),
    consumed: Boolean(kuaishouEticketConsumeResult.value?.consumed),
  }))

  function hydrateKuaishouEticketConfig(data: {
    filePath: string
    source: AdminKuaishouEticketSourceConfig
  }) {
    kuaishouEticketFilePath.value = data.filePath
    shopManager.setShopsFromConfig(data.source.shops)
    kuaishouEticketForm.value = {
      baseUrl: data.source.baseUrl || 'https://s.kwaixiaodian.com',
      selectedShopId: '',
      queryTicketCode: '',
      eTicketId: '',
      oid: '',
      formToken: '',
      num: 1,
      storeId: '0',
    }
    kuaishouEticketForm.value.selectedShopId = shopManager.kuaishouEticketShops.value[0]?.id || ''
    shopManager.expandedKuaishouEticketShopIds.value = shopManager.kuaishouEticketShops.value[0]?.id
      ? [shopManager.kuaishouEticketShops.value[0].id]
      : []
  }

  function buildKuaishouEticketConfigPayload(): AdminKuaishouEticketSourceConfig {
    return {
      enabled: true,
      baseUrl: kuaishouEticketForm.value.baseUrl.trim() || 'https://s.kwaixiaodian.com',
      shops: shopManager.kuaishouEticketShops.value.map((item) => ({
        shopId: item.shopId.trim(),
        kshopName: item.kshopName.trim(),
        cookie: item.cookie.trim(),
        cookieMasked: '',
        hasCookie: Boolean(item.cookie.trim()),
        userAvatar: item.userAvatar.trim(),
        enabled: item.enabled,
      })),
    }
  }

  function addKuaishouEticketShop() {
    const { newSelectedId } = shopManager.addKuaishouEticketShop()
    setKuaishouEticketDebugShop(newSelectedId)
  }

  function removeKuaishouEticketShop(id: string) {
    kuaishouEticketForm.value.selectedShopId = shopManager.removeKuaishouEticketShop(
      id,
      kuaishouEticketForm.value.selectedShopId,
    )
  }

  function setKuaishouEticketDebugShop(id: string) {
    kuaishouEticketForm.value.selectedShopId = id
    shopManager.expandKuaishouEticketShop(id)
  }

  function ensureSelectedKuaishouEticketShop() {
    const selected = activeKuaishouEticketShop.value

    if (!selected) {
      kuaishouEticketResultError.value = '请先新增并选择一个店铺配置'
      return null
    }

    if (!selected.cookie.trim()) {
      kuaishouEticketResultError.value = '当前店铺缺少 Cookie，请先补全后再操作'
      return null
    }

    return selected
  }

  function ensureKuaishouEticketQueryFields() {
    const selected = ensureSelectedKuaishouEticketShop()
    if (!selected) return false

    if (!kuaishouEticketForm.value.queryTicketCode.trim()) {
      kuaishouEticketResultError.value = '请先填写查询券码'
      return false
    }

    return true
  }

  function ensureKuaishouEticketConsumeFields() {
    const selected = ensureSelectedKuaishouEticketShop()
    if (!selected) return false

    if (!kuaishouEticketDetailResult.value?.detail) {
      kuaishouEticketResultError.value =
        '请先查询核销信息，系统会自动带出 eTicketId、oid 和 formToken'
      return false
    }

    return true
  }

  function applyKuaishouEticketDetailToForm(result: AdminKuaishouEticketDetailResult | null) {
    if (!result?.detail) {
      return
    }

    kuaishouEticketForm.value.eTicketId =
      result.detail.eTicketId || kuaishouEticketForm.value.eTicketId
    kuaishouEticketForm.value.oid = result.detail.oid || kuaishouEticketForm.value.oid
    kuaishouEticketForm.value.formToken =
      result.detail.formToken || kuaishouEticketForm.value.formToken

    const leftCount = Number(result.detail.leftCount || 0)
    if (leftCount > 0) {
      kuaishouEticketForm.value.num = leftCount
    }
  }

  async function handleKuaishouEticketResolveShopInfo(shop: EditableKuaishouEticketShop) {
    if (!shop.cookie.trim()) {
      kuaishouEticketResultError.value = '请先为该店铺粘贴 Cookie'
      showError(kuaishouEticketResultError.value)
      return
    }

    kuaishouEticketResolvingShopId.value = shop.id
    kuaishouEticketResultError.value = ''

    try {
      const response = await queryAdminKuaishouEticketShopInfo({
        baseUrl: kuaishouEticketForm.value.baseUrl.trim() || 'https://s.kwaixiaodian.com',
        shopId: shop.shopId.trim(),
        cookie: shop.cookie.trim(),
      })
      kuaishouEticketShopInfoResult.value = response.data
      shop.shopId = response.data.shop.shopId || shop.shopId
      shop.kshopName = response.data.shop.kshopName || shop.kshopName
      shop.userAvatar = response.data.shop.userAvatar || shop.userAvatar
      if (!kuaishouEticketForm.value.selectedShopId) {
        setKuaishouEticketDebugShop(shop.id)
      }
      showSuccess(
        `已识别店铺：${response.data.shop.kshopName || response.data.shop.shopId || '未知店铺'}`,
      )
    } catch (error) {
      kuaishouEticketResultError.value =
        error instanceof Error ? error.message : '读取快手小店店铺信息失败'
      showError(kuaishouEticketResultError.value)
    } finally {
      kuaishouEticketResolvingShopId.value = ''
    }
  }

  async function handleKuaishouEticketSaveSource() {
    kuaishouEticketSaving.value = true
    kuaishouEticketResultError.value = ''

    try {
      const response = await saveAdminKuaishouEticketSourceConfig(
        buildKuaishouEticketConfigPayload(),
      )
      kuaishouEticketFilePath.value = response.data.filePath
      kuaishouEticketForm.value.baseUrl =
        response.data.source.baseUrl || 'https://s.kwaixiaodian.com'
      const previousSelectedShopId = activeKuaishouEticketShop.value?.shopId || ''
      shopManager.setShopsFromConfig(response.data.source.shops)
      kuaishouEticketForm.value.selectedShopId =
        shopManager.findShopByShopId(previousSelectedShopId)?.id ||
        shopManager.kuaishouEticketShops.value[0]?.id ||
        ''
      shopManager.expandedKuaishouEticketShopIds.value = kuaishouEticketForm.value.selectedShopId
        ? [kuaishouEticketForm.value.selectedShopId]
        : []
      showSuccess('快手小店核销配置已保存')
    } catch (error) {
      kuaishouEticketResultError.value =
        error instanceof Error ? error.message : '快手小店核销配置保存失败'
      showError(kuaishouEticketResultError.value)
    } finally {
      kuaishouEticketSaving.value = false
    }
  }

  async function handleKuaishouEticketQueryDetail() {
    if (!ensureKuaishouEticketQueryFields()) {
      return
    }

    const selected = activeKuaishouEticketShop.value
    kuaishouEticketDetailing.value = true
    kuaishouEticketResultError.value = ''
    kuaishouEticketConsumeResult.value = null

    try {
      const response = await queryAdminKuaishouEticketDetail({
        baseUrl: kuaishouEticketForm.value.baseUrl.trim() || 'https://s.kwaixiaodian.com',
        shopId: selected?.shopId.trim(),
        cookie: selected?.cookie.trim(),
        eTicketId: kuaishouEticketForm.value.queryTicketCode.trim(),
      })
      kuaishouEticketDetailResult.value = response.data
      applyKuaishouEticketDetailToForm(response.data)
      showSuccess(
        response.data.ok ? '核销信息查询成功' : response.data.errorMessage || '核销信息已返回',
      )
    } catch (error) {
      kuaishouEticketResultError.value =
        error instanceof Error ? error.message : '查询快手小店核销信息失败'
      showError(kuaishouEticketResultError.value)
    } finally {
      kuaishouEticketDetailing.value = false
    }
  }

  async function handleKuaishouEticketConsume() {
    if (!ensureKuaishouEticketConsumeFields()) {
      return
    }

    const selected = activeKuaishouEticketShop.value
    kuaishouEticketConsuming.value = true
    kuaishouEticketResultError.value = ''

    try {
      const detail = kuaishouEticketDetailResult.value?.detail
      const response = await consumeAdminKuaishouEticket({
        baseUrl: kuaishouEticketForm.value.baseUrl.trim() || 'https://s.kwaixiaodian.com',
        shopId: selected?.shopId.trim(),
        cookie: selected?.cookie.trim(),
        eTicketId: String(detail?.eTicketId || kuaishouEticketForm.value.eTicketId || '').trim(),
        oid: String(detail?.oid || kuaishouEticketForm.value.oid || '').trim(),
        formToken: String(detail?.formToken || kuaishouEticketForm.value.formToken || '').trim(),
        num: Number(kuaishouEticketForm.value.num || 1),
        storeId: kuaishouEticketForm.value.storeId.trim() || '0',
      })
      kuaishouEticketConsumeResult.value = response.data
      showSuccess(
        response.data.ok ? '快手小店核销成功' : response.data.errorMessage || '核销请求已执行',
      )
    } catch (error) {
      kuaishouEticketResultError.value =
        error instanceof Error ? error.message : '执行快手小店核销失败'
      showError(kuaishouEticketResultError.value)
    } finally {
      kuaishouEticketConsuming.value = false
    }
  }

  return {
    kuaishouEticketFilePath,
    kuaishouEticketShops: shopManager.kuaishouEticketShops,
    expandedKuaishouEticketShopIds: shopManager.expandedKuaishouEticketShopIds,
    kuaishouEticketForm,
    kuaishouEticketSaving,
    kuaishouEticketResolvingShopId,
    kuaishouEticketDetailing,
    kuaishouEticketConsuming,
    kuaishouEticketResultError,
    kuaishouEticketShopInfoResult,
    kuaishouEticketDetailResult,
    kuaishouEticketConsumeResult,
    activeKuaishouEticketShop,
    kuaishouEticketStats,
    hydrateKuaishouEticketConfig,
    addKuaishouEticketShop,
    removeKuaishouEticketShop,
    isKuaishouEticketShopExpanded: shopManager.isKuaishouEticketShopExpanded,
    expandKuaishouEticketShop: shopManager.expandKuaishouEticketShop,
    collapseKuaishouEticketShop: shopManager.collapseKuaishouEticketShop,
    toggleKuaishouEticketShop: shopManager.toggleKuaishouEticketShop,
    expandAllKuaishouEticketShops: shopManager.expandAllKuaishouEticketShops,
    collapseAllKuaishouEticketShops: shopManager.collapseAllKuaishouEticketShops,
    setKuaishouEticketDebugShop,
    describeKuaishouEticketShop: shopManager.describeKuaishouEticketShop,
    getKuaishouEticketShopInitial: shopManager.getKuaishouEticketShopInitial,
    handleKuaishouEticketResolveShopInfo,
    handleKuaishouEticketSaveSource,
    handleKuaishouEticketQueryDetail,
    handleKuaishouEticketConsume,
  }
}
