'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendMembershipPlan, yuan } from '@/lib/backend'

function safeCents(value: unknown) {
  return Number.isFinite(Number(value)) ? Number(value) : 0
}

export default function AdminMembershipProductsPage() {
  const [items, setItems] = useState<BackendMembershipPlan[]>([])
  const [keyword, setKeyword] = useState('')
  const [status, setStatus] = useState('all')
  const [error, setError] = useState('')

  useEffect(() => {
    void backend.adminMembershipPlans().then((result) => setItems(result.items)).catch((err) => setError(err instanceof Error ? err.message : '会员方案加载失败'))
  }, [])

  const filteredItems = useMemo(() => {
    const query = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const matchKeyword = !query || [item.level, item.name, item.badge, item.description].some((value) => String(value || '').toLowerCase().includes(query))
      const matchStatus = status === 'all' || item.status === status
      return matchKeyword && matchStatus
    })
  }, [items, keyword, status])

  return (
    <AdminShell title="会员方案" description="维护会员售卖方案、价格、前台状态和权益绑定入口。">
      <div className="space-y-2">
        <div className="grid gap-2 border border-line bg-white p-2 lg:grid-cols-[1fr_150px_auto]">
          <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜索等级、方案、徽标" className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand" />
          <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            <option value="all">全部状态</option>
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
            <option value="offline">已下架</option>
          </select>
          <Link href="/admin/membership/benefits" className="inline-flex h-8 items-center justify-center border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">配置权益</Link>
        </div>
        <div className="border border-line bg-white">
          <div className="grid grid-cols-[100px_1fr_100px_100px_90px_100px] border-b border-line px-3 py-2 text-xs font-extrabold text-soft">
            <span>等级</span><span>方案</span><span>月付</span><span>年付</span><span>权益组</span><span>状态</span>
          </div>
          <div className="max-h-[calc(100vh-178px)] overflow-y-auto">
            {error && <div className="px-3 py-3 text-sm font-bold text-red-700">{error}</div>}
            {filteredItems.length === 0 && !error && <div className="px-3 py-10 text-center text-sm font-bold text-muted">暂无匹配会员方案</div>}
            {filteredItems.map((item) => (
              <Link key={item.productId} href={`/admin/products/membership/${item.productId}/edit`} className="grid grid-cols-[100px_1fr_100px_100px_90px_100px] items-center border-b border-line px-3 py-2 text-xs hover:bg-bg">
                <span className="font-extrabold text-muted">{item.level}</span>
                <span className="min-w-0">
                  <span className="block truncate font-extrabold text-ink">{item.name}</span>
                  <span className="mt-0.5 block truncate text-[11px] font-bold text-muted">{item.badge || '未设徽标'} · {item.ctaLabel || '未设 CTA'}</span>
                </span>
                <span className="font-bold">¥{yuan(safeCents(item.monthlyPriceAmount))}</span>
                <span className="font-bold">¥{yuan(safeCents(item.yearlyPriceAmount))}</span>
                <span className="font-bold text-muted">{item.groups?.length || 0}</span>
                <span className="font-extrabold text-brand">{item.status}</span>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </AdminShell>
  )
}
