'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { RefreshCw, Search, SlidersHorizontal } from 'lucide-react'
import { AdminShell, hasAdminPermission } from '@/components/admin/AdminShell'
import { backend, type BackendMembershipEntitlementAccount, type StaffAccount } from '@/lib/backend'

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

const benefitLabel: Record<string, string> = {
  agent_monthly_quota: '智能体月度额度',
  monthly_ai_report: '会员报告访问',
}

function labelBenefit(code: string) {
  return benefitLabel[code] || code
}

export default function AdminMembershipEntitlementsPage() {
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [items, setItems] = useState<BackendMembershipEntitlementAccount[]>([])
  const [selected, setSelected] = useState<BackendMembershipEntitlementAccount | null>(null)
  const [search, setSearch] = useState('')
  const [benefitCode, setBenefitCode] = useState('')
  const [status, setStatus] = useState('')
  const [delta, setDelta] = useState('')
  const [quotaTotal, setQuotaTotal] = useState('')
  const [note, setNote] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')
  const canAdjustEntitlement = hasAdminPermission(account, 'membership_entitlement:update')

  const benefitOptions = useMemo(() => Array.from(new Set(items.map((item) => item.benefitCode).filter(Boolean))).sort(), [items])

  async function reload() {
    setLoading(true)
    try {
      const [currentAccount, result] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminMembershipEntitlements({ search: search.trim(), benefitCode, status }),
      ])
      setAccount(currentAccount)
      setItems(result.items)
      setSelected((current) => result.items.find((item) => item.id === current?.id) || result.items[0] || null)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '权益额度账户加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  async function submitAdjustment(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!selected) return
    if (!note.trim()) {
      setError('请填写额度调整原因')
      return
    }
    if (!canAdjustEntitlement) {
      setError('当前账号没有会员额度调整权限')
      return
    }
    if (!delta.trim() && !quotaTotal.trim()) {
      setError('请填写增减次数或修正后的总次数')
      return
    }
    if (!window.confirm('确认调整该会员额度账户？此操作会写入额度变更记录。')) return
    setSaving(true)
    setMessage('')
    setError('')
    try {
      const payload: { delta?: number; quotaTotal?: number; note?: string } = { note: note.trim() }
      if (delta.trim()) payload.delta = Number(delta)
      if (quotaTotal.trim()) payload.quotaTotal = Number(quotaTotal)
      const updated = await backend.adjustAdminMembershipEntitlement(selected.id, payload)
      setMessage('额度账户已调整')
      setDelta('')
      setQuotaTotal('')
      setNote('')
      setSelected(updated)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '额度账户调整失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="权益额度账户" description="只管理“次数/额度型”的会员权益，例如智能体月度额度；会员等级、状态和有效期请在会员订阅页调整。">
      {(message || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || message}
        </div>
      )}

      <section className="grid h-[calc(100vh-112px)] min-h-[600px] overflow-hidden border border-line bg-white xl:grid-cols-[minmax(0,1fr)_380px]">
        <div className="min-h-0 flex flex-col overflow-hidden">
          <form className="flex shrink-0 flex-wrap gap-2 border-b border-line px-3 py-2.5" onSubmit={(event) => { event.preventDefault(); void reload() }}>
            <div className="relative min-w-[220px] flex-1">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
              <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="用户、手机号、通行证" className="h-9 w-full border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
            </div>
            <select value={benefitCode} onChange={(event) => setBenefitCode(event.target.value)} className="h-9 border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              <option value="">全部额度权益</option>
              {benefitOptions.map((item) => <option key={item} value={item}>{labelBenefit(item)}</option>)}
            </select>
            <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-9 border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              <option value="">全部状态</option>
              <option value="active">有效</option>
              <option value="expired">过期</option>
              <option value="closed">关闭</option>
            </select>
            <button className="h-9 rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white">查询</button>
            <button type="button" onClick={() => void reload()} className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
              <RefreshCw className="h-4 w-4" />
              刷新
            </button>
          </form>

          <div className="min-h-0 flex-1 overflow-y-auto">
            {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载额度账户...</div>}
            {!loading && items.length === 0 && <div className="px-5 py-8 text-sm font-bold text-muted">暂无额度账户</div>}
            {!loading && items.map((item) => (
              <button key={item.id} type="button" onClick={() => setSelected(item)} className={`grid w-full gap-3 border-b border-line px-4 py-3 text-left hover:bg-bg lg:grid-cols-[1fr_150px_120px_150px] ${selected?.id === item.id ? 'bg-bg' : ''}`}>
                <div className="min-w-0">
                  <div className="truncate text-sm font-extrabold text-ink">{item.userName || item.userPhone || item.passportNo || item.userId}</div>
                  <div className="mt-1 text-xs font-bold text-muted">通行证 {item.passportNo || '-'} · {labelBenefit(item.benefitCode)}</div>
                </div>
                <div className="text-xs font-bold text-muted">
                  <div>周期 {item.periodKey}</div>
                  <div className="mt-1">有效至 {formatDate(item.validTo)}</div>
                </div>
                <div className="text-sm font-extrabold text-ink">{item.quotaRemaining}/{item.quotaTotal}</div>
                <div className="text-xs font-bold text-muted lg:text-right">{item.status}</div>
              </button>
            ))}
          </div>
        </div>

        <aside className="min-h-0 overflow-y-auto border-l border-line bg-bg p-3">
          <div className="mb-2 text-sm font-extrabold text-ink">额度账户详情</div>
          {!selected ? (
            <div className="border border-dashed border-line bg-white px-3 py-8 text-center text-sm font-bold text-muted">选择一条额度账户</div>
          ) : (
            <div className="space-y-3">
              <section className="border border-line bg-white p-3">
                <div className="text-sm font-extrabold text-ink">{labelBenefit(selected.benefitCode)}</div>
                <div className="mt-1 text-[11px] font-bold text-soft">{selected.benefitCode}</div>
                <div className="mt-1 text-xs font-bold text-muted">{selected.userName || selected.passportNo || selected.userId}</div>
                <div className="mt-3 grid grid-cols-3 gap-2 text-center">
                  <Metric label="总次数" value={selected.quotaTotal} />
                  <Metric label="已用" value={selected.quotaUsed} />
                  <Metric label="剩余" value={selected.quotaRemaining} />
                </div>
                <Link href={`/admin/users/${selected.passportNo || selected.userId}`} className="mt-3 inline-flex h-8 items-center rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">查看用户档案</Link>
              </section>

              {canAdjustEntitlement ? (
                <form onSubmit={submitAdjustment} className="border border-line bg-white p-3">
                  <div className="mb-3 flex items-center gap-2 text-sm font-extrabold text-ink">
                    <SlidersHorizontal className="h-4 w-4 text-brand" />
                    额度调整
                  </div>
                  <div className="grid gap-2">
                    <input value={delta} onChange={(event) => setDelta(event.target.value)} type="number" placeholder="增减次数，如 1 或 -1" className="h-9 border border-line px-3 text-sm outline-none focus:border-brand" />
                    <input value={quotaTotal} onChange={(event) => setQuotaTotal(event.target.value)} type="number" placeholder="或直接修正总次数" className="h-9 border border-line px-3 text-sm outline-none focus:border-brand" />
                    <textarea value={note} onChange={(event) => setNote(event.target.value)} required placeholder="调整原因，写入额度变更记录" className="min-h-[76px] border border-line px-3 py-2 text-sm outline-none focus:border-brand" />
                    <button disabled={saving} className="h-9 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white disabled:bg-line-dark">{saving ? '保存中...' : '提交调整'}</button>
                  </div>
                </form>
              ) : (
                <section className="border border-line bg-white p-3">
                  <div className="text-sm font-extrabold text-ink">额度调整</div>
                  <div className="mt-2 rounded-[4px] bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">当前账号仅可查看会员额度账户，不能调整次数或总额度。</div>
                </section>
              )}

              <section className="border border-line bg-white p-3">
                <div className="mb-2 text-sm font-extrabold text-ink">额度变更记录</div>
                <div className="space-y-2">
                  {(selected.ledger || []).length === 0 && <div className="text-xs font-bold text-muted">暂无变更记录</div>}
                  {(selected.ledger || []).map((item) => (
                    <div key={item.id} className="border border-line px-2.5 py-2 text-xs font-bold text-muted">
                      <div className="font-extrabold text-ink">{item.action} · {item.delta}</div>
                      <div className="mt-1">{item.beforeValue} 到 {item.afterValue} · {formatDate(item.createdAt)}</div>
                    </div>
                  ))}
                </div>
              </section>
            </div>
          )}
        </aside>
      </section>
    </AdminShell>
  )
}

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