import type { CartItemType, DeliveryTask, OrderRecord } from '@/components/providers/AppProvider'

export function formatAccountDate(value: string) {
  return new Date(value).toLocaleDateString('zh-CN')
}

export function formatAccountDateTime(value: string) {
  return new Date(value).toLocaleString('zh-CN')
}

export function serviceTypeLabel(type: CartItemType) {
  const labels: Record<CartItemType, string> = {
    course: '课程',
    event: '活动',
    data: '数据服务',
    agent: '智能体',
    expert: '专家预约',
    consulting: '规划咨询',
    membership: '会员',
  }

  return labels[type]
}

export function serviceEntryHref(type: CartItemType, id?: string, backendHref?: string) {
  if (backendHref) return backendHref
  if (type === 'course') return '/account/courses'
  if (type === 'event') return '/account/events'
  if (type === 'data') return id ? `/account/data/${id}` : '/account/data'
  if (type === 'agent') return '/account/agents'
  if (type === 'expert') return '/account/expert-bookings'
  if (type === 'consulting') return '/account/consulting'
  if (type === 'membership') return '/account/membership'
  return '/account'
}

export function serviceActionLabel(type: CartItemType) {
  const labels: Record<CartItemType, string> = {
    course: '继续学习',
    event: '查看报名',
    data: '下载资料',
    agent: '查看交付',
    expert: '查看预约',
    consulting: '查看咨询',
    membership: '查看权益',
  }

  return labels[type]
}

export function parseOrderNote(note?: string) {
  if (!note) return []

  return note
    .split('；')
    .map((part) => part.trim())
    .filter(Boolean)
    .map((part) => {
      const [label, ...rest] = part.split('：')
      return {
        label: rest.length > 0 ? label : '备注',
        value: rest.length > 0 ? rest.join('：') : part,
      }
    })
}

export function orderPrimaryAction(order: OrderRecord) {
  if (order.status === '待支付') return { label: '继续支付', href: '/checkout' }
  const firstItem = order.items[0]
  if (!firstItem) return { label: '查看订单', href: `/account/orders/${order.id}` }
  return {
    label: serviceActionLabel(firstItem.type),
    href: serviceEntryHref(firstItem.type, firstItem.id, firstItem.serviceEntryHref),
  }
}

export function taskEntryHref(task: DeliveryTask) {
  if (task.type === 'expert') return '/account/expert-bookings'
  if (task.type === 'agent') return `/account/delivery/${task.id}`
  if (task.type === 'course') return serviceEntryHref('course')
  if (task.type === 'event') return serviceEntryHref('event')
  if (task.type === 'data') return serviceEntryHref('data')
  if (task.type === 'consulting') return serviceEntryHref('consulting')
  return `/account/delivery/${task.id}`
}

export function taskActionLabel(task: DeliveryTask) {
  if (task.status === '已完成') return '查看记录'
  if (task.status === '待提交资料') return task.type === 'expert' ? '补充背景' : '补充资料'
  return '查看进度'
}
