'use client'

import Link from 'next/link'
import { useState } from 'react'
import { Search, ShieldCheck } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendAdminPassportVerification } from '@/lib/backend'

const levelLabel: Record<string, string> = {
  registered: '注册用户',
  junior: '初级会员',
  senior: '高级会员',
}

const statusLabel: Record<string, string> = {
  active: '正常',
  disabled: '禁用',
}

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

export default function AdminPassportsPage() {
  const [query, setQuery] = useState('')
  const [item, setItem] = useState<BackendAdminPassportVerification | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!query.trim()) return
    setLoading(true)
    setError('')
    try {
      setItem(await backend.adminPassportVerify(query.trim()))
    } catch (err) {
      setItem(null)
      setError(err instanceof Error ? err.message : '通行证核验失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <AdminShell title="通行证核验" description="后台查验前台用户身份与会员状态；现场签到核销请使用独立现场核销入口。">
      <section className="grid h-[calc(100vh-112px)] min-h-[560px] overflow-hidden border border-line bg-white lg:grid-cols-[380px_minmax(0,1fr)]">
        <aside className="border-r border-line bg-bg p-4">
          <form onSubmit={submit} className="border border-line bg-white p-3">
            <div className="mb-3 flex items-center gap-2 text-sm font-extrabold text-ink">
              <ShieldCheck className="h-4 w-4 text-brand" />
              输入通行证号或手机号
            </div>
            <div className="relative">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
              <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="如 DLB2026... 或手机号" className="h-10 w-full border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
            </div>
            <button disabled={loading || !query.trim()} className="mt-3 h-10 w-full rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white disabled:bg-line-dark">{loading ? '核验中...' : '核验'}</button>
          </form>
          {error && <div className="mt-3 rounded-[4px] bg-red-50 px-3 py-2 text-sm font-bold text-red-700">{error}</div>}
        </aside>

        <main className="min-h-0 overflow-y-auto p-4">
          {!item ? (
            <div className="flex h-full items-center justify-center border border-dashed border-line text-sm font-bold text-muted">输入通行证号或手机号后查看核验结果</div>
          ) : (
            <div className="space-y-3">
              <section className="border border-line bg-white p-4">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <div className="text-xl font-extrabold text-ink">{item.displayName || item.passportNo}</div>
                    <div className="mt-1 text-sm font-bold text-muted">通行证 {item.passportNo} · 手机尾号 {item.phoneTail || '-'}</div>
                  </div>
                  <span className={`rounded-[4px] px-2 py-1 text-xs font-extrabold ${item.status === 'disabled' ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>{statusLabel[item.status] || item.status}</span>
                </div>
                <div className="mt-4 grid gap-3 md:grid-cols-4">
                  <Info label="会员等级" value={levelLabel[item.membershipLevel] || item.membershipLevel} />
                  <Info label="会员状态" value={item.membershipStatus || '-'} />
                  <Info label="到期时间" value={formatDate(item.membershipExpiresAt)} />
                  <Info label="剩余天数" value={item.membershipDaysLeft ?? '-'} />
                </div>
                <div className="mt-4 flex flex-wrap gap-2">
                  <Link href={`/admin/users/${item.passportNo}`} className="h-9 rounded-[4px] border border-line px-3 py-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">用户档案</Link>
                  <Link href={`/admin/memberships?search=${encodeURIComponent(item.passportNo)}`} className="h-9 rounded-[4px] border border-line px-3 py-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">会员订阅</Link>
                  <Link href={`/admin/orders?search=${encodeURIComponent(item.passportNo)}`} className="h-9 rounded-[4px] border border-line px-3 py-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">订单流水</Link>
                </div>
              </section>

              <section className="border border-line bg-white p-4">
                <div className="mb-3 text-sm font-extrabold text-ink">业务摘要</div>
                <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
                  <Info label="订单" value={item.summary?.orderCount || 0} />
                  <Info label="课程报名" value={item.summary?.courseRegistrationCount || 0} />
                  <Info label="活动报名" value={item.summary?.eventRegistrationCount || 0} />
                  <Info label="咨询需求" value={item.summary?.consultingRequestCount || 0} />
                  <Info label="数据服务" value={item.summary?.dataServiceRequestCount || 0} />
                  <Info label="专家预约" value={item.summary?.expertBookingCount || 0} />
                </div>
              </section>
            </div>
          )}
        </main>
      </section>
    </AdminShell>
  )
}

function Info({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="border border-line bg-bg px-3 py-2">
      <div className="text-[11px] font-bold text-soft">{label}</div>
      <div className="mt-1 break-words text-sm font-extrabold text-ink">{value}</div>
    </div>
  )
}

