import { computed, type Ref } from 'vue'

import {
  dispatchAdminTaskKuaishouCloudFulfillment,
  prepareAdminTaskKuaishouCloudFulfillment,
  refreshAdminTaskKuaishouCloudRoleInfo,
  returnNumberAdminTaskKuaishouCloudFulfillment,
} from '@/services/admin'
import type { AdminTaskActionResponse, AdminTaskDetail } from '@/types/admin'
import { formatKuaishouRoleInfoLabel } from '@/utils/admin-display'
import { formatAdminDateTime } from '@/utils/admin-time'

import type { ChecklistItem, RoleInfoEntry, SummaryCard } from './types'

export function useAdminTaskKuaishouCloud(
  detail: Ref<AdminTaskDetail | null>,
  runAction: (
    action: () => Promise<{ data: AdminTaskActionResponse }>,
    successMessage: string,
    confirmText: string,
  ) => Promise<void>,
) {
  const kuaishouCloudFlow = computed(() => detail.value?.kuaishouCloudFulfillment || null)
  const kuaishouCloudRole = computed(() => kuaishouCloudFlow.value?.role || null)
  const isKuaishouCloudTask = computed(
    () => detail.value?.task.executorKey === 'kuaishou_ct_assisted',
  )

  const summaryCards = computed<SummaryCard[]>(() => {
    if (!detail.value) {
      return []
    }

    return [
      {
        label: '任务状态',
        value: detail.value.task.status || '-',
        tone: 'blue',
      },
      {
        label: '履约状态',
        value: detail.value.task.deliveryStatus || '-',
        tone: 'green',
      },
      {
        label: '当前角色',
        value: kuaishouCloudRole.value?.name || detail.value.task.roleName || '-',
        tone: 'amber',
      },
      {
        label: '角色 ID',
        value: kuaishouCloudRole.value?.rid || detail.value.task.roleId || '-',
        tone: 'slate',
      },
    ]
  })

  const kuaishouRoleInfoEntries = computed<RoleInfoEntry[]>(() => {
    const rawInfo = kuaishouCloudRole.value?.rawInfo
    if (!rawInfo) {
      return []
    }

    return Object.entries(rawInfo)
      .filter(([, value]) => value !== null && value !== undefined && String(value).trim() !== '')
      .map(([key, value]) => ({
        key,
        label: formatKuaishouRoleInfoLabel(key),
        value: typeof value === 'object' ? JSON.stringify(value) : String(value),
      }))
  })

  const kuaishouCloudChecklist = computed<ChecklistItem[]>(() => {
    const flow = kuaishouCloudFlow.value
    const role = kuaishouCloudRole.value
    if (!flow) {
      return []
    }

    return [
      {
        key: 'ticket',
        label: '核销码校验',
        status: flow.ticket.status || 'pending',
        detail: flow.ticket.verifiedAt
          ? `已于 ${formatAdminDateTime(flow.ticket.verifiedAt)} 校验`
          : '等待客户提交并校验核销码',
      },
      {
        key: 'bind',
        label: '绑定资源',
        status: flow.binding.prepareStatus || 'pending',
        detail: flow.binding.bindPreparedAt
          ? `绑定资源已准备，VN ${flow.binding.vnId || '-'}`
          : '等待准备 Cloud 绑定资源',
      },
      {
        key: 'role',
        label: '角色识别',
        status: role?.status || 'pending',
        detail:
          role?.name || role?.rid
            ? `${role?.name || '-'} / ${role?.rid || '-'}`
            : '客户绑定后刷新角色信息',
      },
      {
        key: 'dispatch',
        label: '发货执行',
        status: flow.dispatch.status || 'pending',
        detail: flow.dispatch.dispatchAt
          ? `已于 ${formatAdminDateTime(flow.dispatch.dispatchAt)} 发货`
          : '等待客服确认绑定并发货',
      },
      {
        key: 'return',
        label: '退还号码',
        status: flow.returnNumber.status || 'pending',
        detail: flow.returnNumber.returnedAt
          ? `已于 ${formatAdminDateTime(flow.returnNumber.returnedAt)} 退号`
          : '发货后执行退还号码',
      },
      {
        key: 'consume',
        label: '快手核销',
        status: flow.consume.status || 'pending',
        detail: flow.consume.consumedAt
          ? `已于 ${formatAdminDateTime(flow.consume.consumedAt)} 完成核销`
          : flow.consume.errorMessage || '等待退号后核销收口',
      },
    ]
  })

  async function submitKuaishouCloudPrepare() {
    if (!detail.value) {
      return
    }

    await runAction(
      () => prepareAdminTaskKuaishouCloudFulfillment(detail.value!.task.taskId),
      '绑定资源已准备完成',
      `确认开始为任务 ${detail.value.task.taskNo} 准备绑定资源吗？系统会自动检查背包、余额并申请虚拟号。`,
    )
  }

  async function submitKuaishouCloudDispatch() {
    if (!detail.value) {
      return
    }

    await runAction(
      () => dispatchAdminTaskKuaishouCloudFulfillment(detail.value!.task.taskId),
      '已完成绑定确认并发货',
      `确认客户已经完成绑定，并立即为任务 ${detail.value.task.taskNo} 执行发货吗？这个动作会把"确认绑定完成"和"发货"合并为一步。`,
    )
  }

  async function submitKuaishouCloudRefreshRoleInfo() {
    if (!detail.value) {
      return
    }

    await runAction(
      () => refreshAdminTaskKuaishouCloudRoleInfo(detail.value!.task.taskId),
      '角色信息已刷新',
      `确认刷新任务 ${detail.value.task.taskNo} 当前云绑定角色信息吗？系统会重新查询 cloudtentacles 的绑定结果。`,
    )
  }

  async function submitKuaishouCloudReturnNumber() {
    if (!detail.value) {
      return
    }

    await runAction(
      () => returnNumberAdminTaskKuaishouCloudFulfillment(detail.value!.task.taskId),
      '号码已退还',
      `确认退还任务 ${detail.value.task.taskNo} 当前使用的虚拟号吗？退号后该流程会正式收口。`,
    )
  }

  return {
    kuaishouCloudFlow,
    kuaishouCloudRole,
    isKuaishouCloudTask,
    summaryCards,
    kuaishouRoleInfoEntries,
    kuaishouCloudChecklist,
    submitKuaishouCloudPrepare,
    submitKuaishouCloudDispatch,
    submitKuaishouCloudRefreshRoleInfo,
    submitKuaishouCloudReturnNumber,
  }
}
