import { computed, type ComputedRef, type Ref } from 'vue'

import { buildTencentBrowserSessionScreenshotUrl } from '@/services/tencent/artifacts'
import type { TencentBrowserActivityInfo } from '@/types/tencent/activity'
import type { TencentBrowserSessionData } from '@/types/tencent/session'

const REDEEM_ALLOWED_STATUSES = new Set(['logged_in', 'ready_to_redeem', 'redeemed'])

export function useTencentBrowserSessionPresentation(options: {
  activityInfo: ComputedRef<TencentBrowserActivityInfo | null>
  hasSession: ComputedRef<boolean>
  loginTypeLabel: ComputedRef<string>
  redeemLoading: Ref<boolean>
  roleConfirmed: Ref<boolean>
  roleReady: ComputedRef<boolean>
  session: Ref<TencentBrowserSessionData | null>
  sessionLoading: Ref<boolean>
  sessionNotice: ComputedRef<string>
}) {
  const {
    activityInfo,
    hasSession,
    loginTypeLabel,
    redeemLoading,
    roleConfirmed,
    roleReady,
    session,
    sessionLoading,
    sessionNotice,
  } = options

  const initButtonLabel = computed(() => `开始初始化 ${loginTypeLabel.value} 登录`)
  const scanInstruction = computed(
    () => `请使用${loginTypeLabel.value}扫描二维码，并在手机上确认登录`,
  )

  const qrImage = computed(() =>
    session.value?.qrImageBase64 ? `data:image/png;base64,${session.value.qrImageBase64}` : '',
  )

  const screenshotUrl = computed(() => {
    if (!session.value?.sessionId || !session.value?.artifacts?.hasScreenshot) {
      return ''
    }

    return buildTencentBrowserSessionScreenshotUrl(session.value.sessionId, session.value.updatedAt)
  })

  const statusLabel = computed(() => {
    if (!hasSession.value) {
      return '待初始化'
    }

    switch (session.value?.status) {
      case 'waiting_scan':
        return '等待扫码'
      case 'scanned':
        return '已扫码待确认'
      case 'logged_in':
        return '页面已登录'
      case 'ready_to_redeem':
        return '可以兑换'
      case 'redeeming':
        return '兑换中'
      case 'redeemed':
        return '已完成'
      case 'failed':
        return '会话异常'
      default:
        return '初始化中'
    }
  })

  const canRedeem = computed(() => {
    if (redeemLoading.value || sessionLoading.value || !session.value?.sessionId) {
      return false
    }

    return (
      REDEEM_ALLOWED_STATUSES.has(String(session.value.status || '')) &&
      roleReady.value &&
      roleConfirmed.value
    )
  })

  const redeemBlockedReason = computed(() => {
    if (!session.value?.sessionId) {
      return `请先选择${loginTypeLabel.value}登录，并手动开始初始化浏览器会话`
    }

    if (redeemLoading.value) {
      return '兑换任务正在执行中'
    }

    if (sessionLoading.value) {
      return '正在刷新浏览器会话状态'
    }

    if (!roleReady.value) {
      return sessionNotice.value || '扫码成功后，后端正在同步角色和大区信息'
    }

    if (!roleConfirmed.value) {
      return '请先确认当前角色与大区无误，再开始兑换'
    }

    if (REDEEM_ALLOWED_STATUSES.has(String(session.value.status || ''))) {
      return ''
    }

    switch (session.value.status) {
      case 'waiting_scan':
        return `请先使用${loginTypeLabel.value}扫码`
      case 'scanned':
        return '请在手机上确认登录后再兑换'
      case 'failed':
        return sessionNotice.value || '浏览器会话异常，请重新生成二维码'
      default:
        return sessionNotice.value || '当前状态还不能开始兑换'
    }
  })

  const finalRedeemMessage = computed(() => {
    const result = session.value?.redeem?.final?.redeem

    if (!result || typeof result !== 'object') {
      return ''
    }

    const record = result as Record<string, unknown>
    return String(record.sMsg || record.msg || '')
  })

  const finalRetCode = computed(() => {
    const result = session.value?.redeem?.final?.redeem

    if (!result || typeof result !== 'object') {
      return ''
    }

    const record = result as Record<string, unknown>
    return String(record.iRet ?? '')
  })

  const roleFacts = computed(() => [
    {
      label: '登录昵称',
      value: activityInfo.value?.nickname || '等待扫码登录',
    },
    {
      label: '当前角色',
      value: activityInfo.value?.role?.roleName || '后端浏览器同步中',
      accent: true,
    },
    {
      label: '角色 ID',
      value: activityInfo.value?.role?.roleId || '未识别',
    },
    {
      label: '验证码',
      value:
        activityInfo.value?.form?.verifyValue ||
        (activityInfo.value?.verify?.visible ? '等待识别' : '等待显示'),
    },
  ])

  const resultFacts = computed(() => [
    {
      label: '业务返回码',
      value: finalRetCode.value || '-',
    },
    {
      label: '业务消息',
      value: finalRedeemMessage.value || '尚未兑换',
    },
    {
      label: 'OCR 尝试次数',
      value: String(session.value?.redeem?.attempts.length || 0),
    },
    {
      label: '证明截图',
      value: session.value?.artifacts?.hasScreenshot ? '已生成' : '未生成',
    },
  ])

  const redeemButtonLabel = computed(() => '开始兑换')
  const screenshotEmptyTitle = computed(() =>
    session.value?.status === 'redeemed' ? '本次没有可展示的截图' : '等待截图',
  )
  const screenshotEmptyMessage = computed(() =>
    session.value?.status === 'redeemed'
      ? '本次兑换可能未生成截图，或截图产物已被后端配置关闭。'
      : '如本次兑换生成了结果截图，这里会展示。',
  )

  return {
    canRedeem,
    initButtonLabel,
    qrImage,
    redeemBlockedReason,
    redeemButtonLabel,
    resultFacts,
    roleFacts,
    scanInstruction,
    screenshotEmptyMessage,
    screenshotEmptyTitle,
    screenshotUrl,
    statusLabel,
  }
}
