'use client'

import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { BadgeCheck, CircleAlert, Search } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { QrCodeSvg } from '@/components/shared/QrCodeSvg'
import { backend, type BackendPassportVerification } from '@/lib/backend'

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

const expertStatusLabel: Record<string, string> = {
  draft: '专家草稿',
  published: '认证专家',
  offline: '专家已下线',
}

export function PassportVerifyClient() {
  const searchParams = useSearchParams()
  const initialCode = searchParams.get('code') || ''
  const [code, setCode] = useState(initialCode)
  const [result, setResult] = useState<BackendPassportVerification | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const normalizedCode = useMemo(() => code.trim().toUpperCase(), [code])

  useEffect(() => {
    setCode(initialCode)
  }, [initialCode])

  useEffect(() => {
    if (!initialCode) return
    void verify(initialCode)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialCode])

  async function verify(nextCode = normalizedCode) {
    const passportNo = nextCode.trim().toUpperCase()
    if (!passportNo) {
      setError('请填写通行证编号')
      setResult(null)
      return
    }
    setLoading(true)
    setError('')
    try {
      const item = await backend.passportVerification(passportNo)
      setResult(item)
    } catch (err) {
      setResult(null)
      setError(err instanceof Error ? err.message : '通行证核验失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="min-h-screen bg-[#f5f7fb] px-6 py-10">
      <div className="mx-auto max-w-[880px]">
        <Link href="/" className="text-sm font-bold text-muted hover:text-brand">返回首页</Link>

        <section className="mt-5 border border-line bg-white p-6 shadow-[0_12px_34px_rgba(15,23,42,0.05)] md:p-8">
          <div className="flex flex-col gap-5 md:flex-row md:items-start md:justify-between">
            <div>
              <div className="text-sm font-extrabold text-brand">大连市大数据研究院</div>
              <h1 className="mt-2 text-3xl font-extrabold text-ink">会员通行证核验</h1>
              <p className="mt-3 max-w-[560px] text-sm leading-7 text-muted">输入或扫描会员通行证后，可核验账号状态、会员身份和专家认证状态。</p>
            </div>
            <div className="w-28 shrink-0">
              <QrCodeSvg value={normalizedCode || 'PASSPORT-VERIFY'} label="通行证核验二维码" className="w-full rounded-[4px] shadow-[0_8px_24px_rgba(15,23,42,0.06)]" />
            </div>
          </div>

          <div className="mt-7 flex flex-col gap-3 sm:flex-row">
            <input
              value={code}
              onChange={(event) => setCode(event.target.value)}
              placeholder="请输入通行证编号，如 KQHVP-58209"
              className="h-11 flex-1 rounded-[4px] border border-line px-3 text-sm font-bold uppercase outline-none focus:border-brand"
            />
            <button onClick={() => void verify()} disabled={loading} className="inline-flex h-11 items-center justify-center gap-2 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
              <Search className="h-4 w-4" />
              {loading ? '核验中...' : '核验'}
            </button>
          </div>

          {error && (
            <div className="mt-5 flex items-center gap-2 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">
              <CircleAlert className="h-4 w-4" />
              {error}
            </div>
          )}

          {result && (
            <div className="mt-6 border border-line bg-bg p-5">
              <div className="flex items-center gap-2 text-base font-extrabold text-ink">
                <BadgeCheck className="h-5 w-5 text-green" />
                通行证有效
              </div>
              <div className="mt-5 grid gap-3 text-sm sm:grid-cols-2">
                <div><span className="font-bold text-muted">通行证编号：</span><span className="font-extrabold text-ink">{result.passportNo}</span></div>
                <div><span className="font-bold text-muted">账号状态：</span><span className="font-extrabold text-ink">{result.status === 'active' ? '正常' : '已禁用'}</span></div>
                <div><span className="font-bold text-muted">显示名称：</span><span className="font-extrabold text-ink">{result.displayName || '未填写'}</span></div>
                <div><span className="font-bold text-muted">手机号尾号：</span><span className="font-extrabold text-ink">{result.phoneTail || '-'}</span></div>
                <div><span className="font-bold text-muted">所属机构：</span><span className="font-extrabold text-ink">{result.organization || '未填写'}</span></div>
                <div><span className="font-bold text-muted">会员身份：</span><span className="font-extrabold text-ink">{levelLabel[result.membershipLevel] || result.membershipLevel}</span></div>
                <div><span className="font-bold text-muted">会员状态：</span><span className="font-extrabold text-ink">{result.membershipStatus === 'active' ? '有效' : result.membershipStatus === 'expiring' ? '临期' : result.membershipStatus === 'expired' ? '已过期' : '未开通'}</span></div>
                <div><span className="font-bold text-muted">会员有效期：</span><span className="font-extrabold text-ink">{result.membershipExpiresAt ? new Date(result.membershipExpiresAt).toLocaleString('zh-CN') : '-'}</span></div>
                <div><span className="font-bold text-muted">专家状态：</span><span className="font-extrabold text-ink">{expertStatusLabel[result.expertStatus] || '未认证专家'}</span></div>
                <div><span className="font-bold text-muted">核验时间：</span><span className="font-extrabold text-ink">{new Date(result.verifiedAt).toLocaleString('zh-CN')}</span></div>
              </div>
            </div>
          )}
        </section>
      </div>
    </main>
  )
}
