'use client'

import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { Suspense, useEffect, useState } from 'react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { AccountEmptyState } from '@/components/account/AccountEmptyState'
import { formatAccountDateTime } from '@/components/account/account-utils'
import type { CartItemType, DeliveryTask, OrderItem, OrderRecord } from '@/components/providers/AppProvider'
import { useApp } from '@/components/providers/AppProvider'
import { backend, mapBackendOrder, mapBackendTask } from '@/lib/backend'

const orderTypes: CartItemType[] = ['course', 'event', 'data', 'agent', 'expert', 'consulting', 'membership']

const orderTypeLabels: Record<CartItemType, string> = {
  course: '课程',
  event: '活动',
  data: '数据',
  agent: '智能体',
  expert: '专家预约',
  consulting: '规划咨询',
  membership: '会员',
}

function ordersByType(orders: OrderRecord[], type: CartItemType) {
  return orders.filter((order) => order.items.some((item) => item.type === type))
}

function findTask(tasks: DeliveryTask[], order: OrderRecord, item: OrderItem) {
  return tasks.find((task) => task.orderId === order.id && task.type === item.type && task.id.includes(item.id))
}

function itemStatus(type: CartItemType, order: OrderRecord, task?: DeliveryTask) {
  if (order.status === '待支付') return '待支付'
  if (order.status === '已关闭') return '已关闭'
  if (type === 'data') return task?.status || '已支付'
  if (type === 'agent') return task ? task.steps[task.currentStep] : '提交部署资料'
  if (type === 'expert') {
    if (task?.status === '已完成') return '已完成'
    if (task?.status === '交付中' || task?.status === '资料审核中') return '预约中'
    return '已支付'
  }
  if (type === 'event') return task?.status || '已支付'
  if (type === 'course') return task?.status || '已支付'
  if (type === 'consulting') return task?.status || '待受理'
  if (type === 'membership') return order.status === '已支付' ? '已开通' : order.status
  return order.status
}

function statusTone(status: string) {
  if (status === '-' || status === '已完成' || status === '已报名' || status === '已开通') return 'bg-brand/10 text-brand'
  if (status.includes('审核') || status.includes('配置') || status.includes('预约中')) return 'bg-amber-50 text-amber-700'
  return 'bg-bg text-muted'
}

function AccountOrdersContent() {
  const searchParams = useSearchParams()
  const { user, token } = useApp()
  const [orders, setOrders] = useState<OrderRecord[]>([])
  const [deliveryTasks, setDeliveryTasks] = useState<DeliveryTask[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!token) return
    let mounted = true
    setLoading(true)
    Promise.all([
      backend.accountOrders(token),
      backend.accountTasks(token),
    ])
      .then(([orderResult, taskResult]) => {
        if (!mounted) return
        setOrders(orderResult.items.map(mapBackendOrder))
        setDeliveryTasks(taskResult.items.map(mapBackendTask))
        setError('')
      })
      .catch((err) => {
        if (mounted) setError(err instanceof Error ? err.message : '订单加载失败')
      })
      .finally(() => {
        if (mounted) setLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [token])

  if (!user) return <AccountAuthPrompt message="登录后可查看订单记录。" />
  if (loading) return <div className="rounded-[4px] border border-line bg-white p-8 text-sm font-bold text-muted">正在加载订单...</div>

  const selectedType = searchParams.get('type')
  const visibleTypes = orderTypes.includes(selectedType as CartItemType) ? [selectedType as CartItemType] : orderTypes
  const groupedOrders = visibleTypes
    .map((type) => ({ type, orders: ordersByType(orders, type) }))
    .filter((group) => group.orders.length > 0)

  return (
    <div>
      {error && <div className="mb-4 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
      {orders.length === 0 ? (
        <AccountEmptyState title="还没有订单" description="购买课程、活动、数据服务或智能体后，订单会按商品单独出现在这里。" actionLabel="浏览课程" actionHref="/courses" />
      ) : (
        <div className="space-y-6">
          {groupedOrders.length === 0 ? (
            <AccountEmptyState title={`暂无${selectedType ? orderTypeLabels[selectedType as CartItemType] : ''}订单`} description="切换其他分类看看，或继续浏览服务内容。" />
          ) : (
            groupedOrders.map((group) => (
              <section key={group.type}>
                <div className="mb-2 text-sm font-extrabold text-muted">{orderTypeLabels[group.type]}</div>
                <div className="overflow-hidden rounded-[4px] border border-line bg-white">
                  {group.orders.flatMap((order) => order.items
                    .filter((item) => item.type === group.type)
	                    .map((item) => {
	                      const task = findTask(deliveryTasks, order, item)
	                      const status = itemStatus(item.type, order, task)

                      return (
                        <Link
                          key={`${group.type}-${order.id}-${item.id}`}
                          href={`/account/orders/${order.id}`}
                          className="grid border-b border-line transition last:border-b-0 hover:bg-[#f8fbff] md:grid-cols-[1fr_104px]"
                        >
                          <div className="px-4 py-3">
                            <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                              <div>
                                <div className="text-[15px] font-extrabold leading-6 text-ink">{item.title}</div>
                                {item.meta && <div className="mt-0.5 text-sm text-muted">{item.meta}</div>}
                              </div>
                            </div>

                            <div className="mt-3 grid gap-x-5 gap-y-1.5 text-sm md:grid-cols-3 xl:grid-cols-5">
                              <div>
                                <div className="text-xs font-bold text-soft">订单号</div>
                                <div className="mt-0.5 break-all font-extrabold text-ink">{order.id}</div>
                              </div>
                              <div>
                                <div className="text-xs font-bold text-soft">结算编号</div>
                                <div className="mt-0.5 break-all font-extrabold text-ink">{order.settlementNo || '-'}</div>
                              </div>
                              <div>
                                <div className="text-xs font-bold text-soft">金额</div>
                                <div className="mt-0.5 font-extrabold text-ink">¥{order.subtotal.toLocaleString()}</div>
                              </div>
                              <div>
                                <div className="text-xs font-bold text-soft">实付金额</div>
                                <div className="mt-0.5 font-extrabold text-brand">¥{order.total.toLocaleString()}</div>
                              </div>
                              <div>
                                <div className="text-xs font-bold text-soft">购买时间</div>
                                <div className="mt-0.5 font-extrabold text-ink">{formatAccountDateTime(order.createdAt)}</div>
                              </div>
                            </div>
                          </div>

                          <div className={`grid min-h-[44px] place-items-center border-t border-line px-3 text-center text-sm font-extrabold md:min-h-full md:border-l md:border-t-0 ${statusTone(status)}`}>
                            {status}
                          </div>
                        </Link>
                      )
                    }))}
                </div>
              </section>
            ))
          )}
        </div>
      )}
    </div>
  )
}

export default function AccountOrdersPage() {
  return (
    <Suspense fallback={<div className="py-10 text-sm font-bold text-muted">正在加载订单...</div>}>
      <AccountOrdersContent />
    </Suspense>
  )
}
