'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { ArrowLeft, Pencil, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendCoupon, type BackendCouponRedemption, yuan } from '@/lib/backend'

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

export default function AdminCouponRedemptionsPage() {
  const params = useParams<{ id: string }>()
  const couponId = params.id
  const [coupon, setCoupon] = useState<BackendCoupon | null>(null)
  const [items, setItems] = useState<BackendCouponRedemption[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  async function reload() {
    setLoading(true)
    try {
      const [couponResult, redemptionResult] = await Promise.all([
        backend.adminCoupon(couponId),
        backend.adminCouponRedemptions(couponId),
      ])
      setCoupon(couponResult)
      setItems(redemptionResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '使用记录加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void reload()
    }, 0)
    return () => window.clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [couponId])

  return (
    <AdminShell title="优惠码使用记录" description="查看优惠码对应订单、用户、减免金额和当时命中的规则快照。">
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
        <Link href="/admin/coupons" className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-3.5 w-3.5" />
          返回优惠码列表
        </Link>
        <div className="flex items-center gap-2">
          {coupon && (
            <Link href={`/admin/coupons/${coupon.id}/edit`} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-brand hover:bg-brand-light">
              <Pencil className="h-3.5 w-3.5" />
              编辑优惠码
            </Link>
          )}
          <button type="button" onClick={() => void reload()} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
            <RefreshCw className="h-3.5 w-3.5" />
            刷新
          </button>
        </div>
      </div>

      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      {coupon && (
        <section className="mb-3 grid gap-3 border border-line bg-white p-4 text-sm md:grid-cols-4">
          <div>
            <div className="text-xs font-extrabold text-soft">优惠码</div>
            <div className="mt-1 font-extrabold text-ink">{coupon.code}</div>
            <div className="mt-1 text-xs font-bold text-muted">{coupon.name}</div>
          </div>
          <div>
            <div className="text-xs font-extrabold text-soft">用量</div>
            <div className="mt-1 font-extrabold text-ink">{coupon.usedQuantity}/{coupon.totalQuantity}</div>
            <div className="mt-1 text-xs font-bold text-muted">剩余 {coupon.remainingQuantity}</div>
          </div>
          <div>
            <div className="text-xs font-extrabold text-soft">累计减免</div>
            <div className="mt-1 font-extrabold text-ink">¥{yuan(coupon.usedDiscountAmount || 0).toLocaleString()}</div>
            <div className="mt-1 text-xs font-bold text-muted">{coupon.budgetAmount ? `预算 ¥${yuan(coupon.budgetAmount).toLocaleString()}` : '无预算上限'}</div>
          </div>
          <div>
            <div className="text-xs font-extrabold text-soft">有效期</div>
            <div className="mt-1 font-bold text-ink">{formatDate(coupon.startsAt)}</div>
            <div className="mt-1 text-xs font-bold text-muted">至 {formatDate(coupon.endsAt)}</div>
          </div>
        </section>
      )}

      <section className="overflow-x-auto border border-line bg-white">
        <table className="min-w-[920px] w-full border-collapse text-left text-sm">
          <thead className="border-b border-line bg-bg text-xs font-extrabold text-soft">
            <tr>
              <th className="px-4 py-3">订单</th>
              <th className="px-4 py-3">用户</th>
              <th className="px-4 py-3">减免金额</th>
              <th className="px-4 py-3">优惠基数</th>
              <th className="px-4 py-3">使用时间</th>
              <th className="px-4 py-3">规则快照</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan={6} className="px-4 py-8 text-sm font-bold text-muted">正在加载使用记录...</td></tr>
            )}
            {!loading && items.length === 0 && (
              <tr><td colSpan={6} className="px-4 py-8 text-sm font-bold text-muted">暂无使用记录</td></tr>
            )}
            {!loading && items.map((item) => (
              <tr key={item.id} className="border-b border-line align-top hover:bg-bg">
                <td className="px-4 py-3">
                  <div className="font-extrabold text-ink">{item.orderNo || item.orderId}</div>
                  {item.orderId && <div className="mt-1 text-xs font-bold text-soft">{item.orderId}</div>}
                </td>
                <td className="px-4 py-3">
                  <div className="font-bold text-ink">{item.userName || item.passportNo || item.userPhone || item.userId}</div>
                  <div className="mt-1 text-xs font-bold text-muted">通行证 {item.passportNo || '-'}</div>
                  <div className="mt-1 text-xs font-bold text-muted">手机 {item.userPhone || '-'}</div>
                </td>
                <td className="px-4 py-3 font-extrabold text-brand">¥{yuan(item.discountAmount).toLocaleString()}</td>
                <td className="px-4 py-3 font-bold text-muted">¥{yuan(item.discountBaseAmount || 0).toLocaleString()}</td>
                <td className="px-4 py-3 font-bold text-muted">{formatDate(item.createdAt)}</td>
                <td className="px-4 py-3">
                  <details className="max-w-[260px]">
                    <summary className="cursor-pointer text-xs font-extrabold text-brand">查看</summary>
                    <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded-[4px] bg-bg p-2 text-[11px] leading-relaxed text-muted">{JSON.stringify(item.ruleSnapshot || {}, null, 2)}</pre>
                  </details>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </AdminShell>
  )
}
