'use client'

import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { ArrowRight } from 'lucide-react'
import type { OrderRecord } from '@/components/providers/AppProvider'
import { useApp } from '@/components/providers/AppProvider'
import { backend, mapBackendOrder } from '@/lib/backend'

export function CheckoutSuccessClient() {
  const searchParams = useSearchParams()
  const { hydrated, orders, token } = useApp()
  const orderId = searchParams.get('orderId') || ''
  const cachedOrder = orders.find((item) => item.id === orderId)
  const [loadedOrder, setLoadedOrder] = useState<OrderRecord | null>(null)
  const order = cachedOrder || loadedOrder
  const pending = order?.status === '待支付'
  const membershipItem = order?.items.find((item) => item.type === 'membership')
  const expertItem = order?.items.find((item) => item.type === 'expert')
  const dataServiceRequestId = searchParams.get('dataServiceRequestId') || ''
  const isMembershipOrder = Boolean(membershipItem)
  const isExpertOrder = Boolean(expertItem)
  const isDataServiceOrder = Boolean(dataServiceRequestId)
  const title = pending ? '订单已提交' : isMembershipOrder ? '会员开通完成' : isExpertOrder ? '专家预约已提交' : isDataServiceOrder ? '数据服务已付款' : '支付完成'
  const primaryHref = pending ? '/account/orders' : isMembershipOrder ? '/account/membership' : isExpertOrder ? '/account/expert-bookings' : isDataServiceOrder ? `/account/data/${dataServiceRequestId}` : '/account'
  const primaryText = pending ? '查看订单' : isMembershipOrder ? '查看会员权益' : isExpertOrder ? '查看预约进度' : isDataServiceOrder ? '查看服务进度' : '进入个人中心'

  useEffect(() => {
    if (!hydrated || cachedOrder || !token || !orderId) return
    let cancelled = false
    void backend.accountOrders(token)
      .then((result) => {
        if (cancelled) return
        const matched = result.items.find((item) => item.orderNo === orderId || item.id === orderId)
        setLoadedOrder(matched ? mapBackendOrder(matched) : null)
      })
      .catch(() => {
        if (!cancelled) setLoadedOrder(null)
      })
    return () => {
      cancelled = true
    }
  }, [cachedOrder, hydrated, orderId, token])

  return (
    <section className="relative grid min-h-[calc(100vh-70px)] place-items-center overflow-hidden bg-[linear-gradient(135deg,#f6f9ff_0%,#eef5ff_48%,#ffffff_48%,#ffffff_100%)] px-6 py-12 md:min-h-[calc(100vh-106px)]">
      <div className="absolute left-0 top-0 h-full w-[22vw] border-r border-white/70 bg-white/25" aria-hidden />
      <div className="absolute bottom-0 right-0 h-36 w-[44vw] border-t border-line bg-bg/70" aria-hidden />

      <div className="relative w-full max-w-[900px] bg-white/82 p-10 shadow-[0_28px_90px_rgba(15,23,42,0.14)] backdrop-blur-md md:p-14">
        <div className="flex flex-col gap-8 md:flex-row md:items-center md:justify-between">
          <div>
            <h1 className="text-[38px] font-extrabold leading-tight text-ink md:text-[52px]">
              {title}
            </h1>
            {isMembershipOrder && (
              <p className="mt-3 text-sm font-bold text-muted">{membershipItem?.title} 已生效，可返回会员页查看当前权益。</p>
            )}
            {isExpertOrder && (
              <p className="mt-3 text-sm font-bold text-muted">{expertItem?.title} 已提交，后续确认和咨询进度可在个人中心查看。</p>
            )}
            {isDataServiceOrder && (
              <p className="mt-3 text-sm font-bold text-muted">业务员会继续整理数据服务成果，完成后可在我的数据服务中下载。</p>
            )}
            {pending && (
              <p className="mt-3 text-sm font-bold text-muted">支付结果仍在确认中，订单完成支付后会自动开通对应权益。</p>
            )}
          </div>

          {order && (
            <div className="min-w-[240px] border-l-4 border-brand bg-bg/80 p-5">
              <div className="text-xs font-bold text-muted">订单号</div>
              <div className="mt-1 break-all text-sm font-extrabold text-ink">{order.id}</div>
            </div>
          )}
        </div>

        <div className="mt-10 flex flex-wrap gap-3 border-t border-line pt-8">
          <Link href={primaryHref} className="inline-flex h-12 items-center justify-center gap-2 rounded-[4px] bg-brand px-7 text-sm font-extrabold text-white hover:bg-brand-dark">
            {primaryText}
            <ArrowRight className="h-4 w-4" />
          </Link>
          <Link href="/" className="inline-flex h-12 items-center justify-center rounded-[4px] border border-line px-7 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">返回首页</Link>
        </div>
      </div>
    </section>
  )
}
