'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { ArrowLeft, ExternalLink, FileText, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendOrder, yuan } from '@/lib/backend'

const statusLabel: Record<string, string> = {
  pending_payment: '待支付',
  paid: '已支付',
  closed: '已关闭',
}

function formatDate(value?: string) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

export default function AdminOrderDetailPage() {
  const params = useParams<{ id: string }>()
  const orderKey = useMemo(() => decodeURIComponent(String(params.id || '')), [params.id])
  const [order, setOrder] = useState<BackendOrder | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  async function reload() {
    setLoading(true)
    try {
      const current = await backend.adminOrder(orderKey)
      setOrder(current)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '订单加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orderKey])

  return (
    <AdminShell title="订单详情" description="查看订单编号、结算批次、商品明细、金额和支付状态。">
      <div className="mb-3 flex flex-wrap justify-between gap-2">
        <Link href="/admin/orders" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-4 w-4" />
          返回订单流水
        </Link>
        <div className="flex flex-wrap gap-1.5">
          {order && (
            <Link href={`/admin/payments?search=${encodeURIComponent(order.orderNo)}`} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
              <ExternalLink className="h-4 w-4" />
              支付记录
            </Link>
          )}
          <button type="button" onClick={() => void reload()} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
            <RefreshCw className="h-4 w-4" />
            刷新
          </button>
        </div>
      </div>

      {loading && <div className="border border-line bg-white px-5 py-10 text-sm font-bold text-muted">正在加载订单...</div>}
      {!loading && error && <div className="border border-line bg-white px-5 py-10 text-sm font-bold text-red-700">{error}</div>}

      {!loading && order && (
        <div className="grid h-[calc(100vh-145px)] min-h-[560px] gap-3 overflow-hidden xl:grid-cols-[1fr_340px]">
          <section className="min-h-0 overflow-y-auto border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <h2 className="text-lg font-extrabold text-ink">{order.orderNo}</h2>
              <div className="mt-1 text-[11px] font-bold text-muted">结算批次 {order.settlementNo || '-'} · 用户 {order.userPhone || '-'} · {formatDate(order.createdAt)}</div>
            </div>
            <div className="p-4">
              <div className="text-sm font-extrabold text-ink">订单商品</div>
              <div className="mt-3 divide-y divide-line border border-line">
                {order.items.length === 0 ? (
                  <div className="px-4 py-8 text-center text-sm font-bold text-red-700">异常订单：无商品明细</div>
                ) : order.items.map((item) => (
                  <div key={`${item.productId}-${item.titleSnapshot}`} className="grid gap-3 px-3 py-2 text-sm md:grid-cols-[1fr_70px_110px] md:items-center">
                    <div>
                      <div className="font-extrabold text-ink">{item.titleSnapshot}</div>
                      <div className="mt-1 text-xs font-bold text-muted">{item.productType} · {item.productId}</div>
                    </div>
                    <div className="text-xs font-bold text-muted">x{item.quantity}</div>
                    <div className="text-sm font-extrabold text-brand">¥{yuan(item.payableAmount).toLocaleString()}</div>
                  </div>
                ))}
              </div>
            </div>
          </section>

          <aside className="min-h-0 overflow-y-auto border border-line bg-white p-4">
            <div className="text-sm font-extrabold text-ink">金额信息</div>
            <div className="mt-4 space-y-2.5 text-sm font-bold">
              <div className="flex justify-between gap-4"><span className="text-muted">小计</span><span className="text-ink">¥{yuan(order.subtotalAmount).toLocaleString()}</span></div>
              <div className="flex justify-between gap-4"><span className="text-muted">会员折扣</span><span className="text-ink">- ¥{yuan(order.memberDiscountAmount).toLocaleString()}</span></div>
              <div className="flex justify-between gap-4"><span className="text-muted">优惠码</span><span className="text-ink">- ¥{yuan(order.couponDiscountAmount).toLocaleString()}</span></div>
              <div className="flex justify-between gap-4 border-t border-line pt-3"><span className="text-muted">应付</span><span className="text-xl font-extrabold text-brand">¥{yuan(order.totalAmount).toLocaleString()}</span></div>
              <div className="flex justify-between gap-4"><span className="text-muted">已收</span><span className="text-ink">¥{yuan(order.status === 'paid' || order.status === 'completed' ? order.paidAmount : 0).toLocaleString()}</span></div>
              <div className="flex justify-between gap-4"><span className="text-muted">状态</span><span className="text-ink">{statusLabel[order.status] || order.status}</span></div>
            </div>
            <div className="mt-6 border-t border-line pt-5">
              <div className="flex items-center gap-2 text-base font-extrabold text-ink">
                <FileText className="h-4 w-4 text-brand" />
                发票申请
              </div>
              {order.invoiceApplication ? (
                <div className="mt-4 space-y-3 text-sm font-bold">
                  <div className="flex justify-between gap-4"><span className="text-muted">申请单号</span><span className="text-ink">{order.invoiceApplication.invoiceNo}</span></div>
                  <div className="flex justify-between gap-4"><span className="text-muted">状态</span><span className="text-brand">{order.invoiceStatus || order.invoiceApplication.status}</span></div>
                  <div className="flex justify-between gap-4"><span className="text-muted">抬头</span><span className="text-right text-ink">{order.invoiceApplication.title}</span></div>
                  <Link href={`/admin/invoices/${encodeURIComponent(order.invoiceApplication.invoiceNo)}`} className="inline-flex h-10 w-full items-center justify-center gap-2 rounded-[4px] border border-line text-sm font-bold text-muted hover:border-brand hover:text-brand">
                    <ExternalLink className="h-4 w-4" />
                    打开发票详情
                  </Link>
                </div>
              ) : (
                <div className="mt-3 rounded-[4px] bg-bg p-3 text-xs font-bold leading-6 text-muted">该订单暂无发票申请。</div>
              )}
            </div>
          </aside>
        </div>
      )}
    </AdminShell>
  )
}
