'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { Gift, PencilLine, Search, TimerReset } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendMembershipSubscription, type BackendStaffAccount, type StaffAccount } from '@/lib/backend'

const tierLabel: Record<string, string> = {
  junior: '初级会员',
  senior: '高级会员',
}

const statusLabel: Record<string, string> = {
  active: '有效',
  past_due: '扣款待处理',
  expired: '已到期',
  canceled: '已取消',
  refunded: '已关闭',
}

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

function toDateTimeInput(value?: string | null) {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
  return local.toISOString().slice(0, 16)
}

export default function AdminMembershipsPage() {
  const [account, setAccount] = useState<StaffAccount | null>(null)
  const [items, setItems] = useState<BackendMembershipSubscription[]>([])
  const [staff, setStaff] = useState<BackendStaffAccount[]>([])
  const [search, setSearch] = useState('')
  const [tier, setTier] = useState('')
  const [status, setStatus] = useState('active')
  const [grantUser, setGrantUser] = useState('')
  const [grantTier, setGrantTier] = useState<'junior' | 'senior'>('junior')
  const [grantDays, setGrantDays] = useState('30')
  const [editing, setEditing] = useState<BackendMembershipSubscription | null>(null)
  const [adjustTier, setAdjustTier] = useState<'junior' | 'senior'>('junior')
  const [adjustStatus, setAdjustStatus] = useState<BackendMembershipSubscription['status']>('active')
  const [adjustStartsAt, setAdjustStartsAt] = useState('')
  const [adjustExpiresAt, setAdjustExpiresAt] = useState('')
  const [adjustReason, setAdjustReason] = useState('')
  const [managerEditing, setManagerEditing] = useState<BackendMembershipSubscription | null>(null)
  const [managerStaffId, setManagerStaffId] = useState('')
  const [managerNote, setManagerNote] = useState('')
  const [loading, setLoading] = useState(false)
  const [savingAdjustment, setSavingAdjustment] = useState(false)
  const [savingManager, setSavingManager] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')
  const canUpdateMembership = Boolean(account?.permissions?.includes('*') || account?.permissions?.includes('membership_subscription:update'))

  async function reload(next = { search, tier, status }) {
    setLoading(true)
    try {
      const [currentAccount, memberships, staffResult] = await Promise.all([
        account ? Promise.resolve(account) : backend.staffMe(),
        backend.adminMemberships(next),
        backend.adminStaffAccounts({ status: 'active' }).catch(() => ({ items: [] as BackendStaffAccount[] })),
      ])
      setAccount(currentAccount)
      setItems(memberships.items)
      setStaff(staffResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '会员订阅加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void reload({ search: '', tier: '', status: 'active' })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  async function runJob(kind: 'expire') {
    try {
      setMessage('')
      setError('')
      if (kind === 'expire') {
        const result = await backend.runMembershipExpiryJob()
        setMessage(`到期处理完成：${result.expiredCount} 条到期，${result.downgradedCount} 个用户降级`)
      }
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '任务执行失败')
    }
  }

  async function submitGrant(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!window.confirm(`确认给 ${grantUser.trim() || '该用户'} 手动赠送 ${tierLabel[grantTier]} ${grantDays || 30} 天？`)) return
    try {
      const durationDays = Math.max(1, Number(grantDays || 30))
      await backend.manualGrantMembership({ userId: grantUser.trim(), passportNo: grantUser.trim(), phone: grantUser.trim(), tier: grantTier, durationDays })
      setMessage('会员已手动赠送')
      setGrantUser('')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '手动赠送失败')
    }
  }

  async function operateMembership(item: BackendMembershipSubscription, mode: 'period_end' | 'immediate') {
    if (!window.confirm(mode === 'period_end' ? '确认将该会员设置为到期不续？' : '确认立即关闭该会员？此操作会影响用户当前会员权益。')) return
    try {
      setMessage('')
      setError('')
      await backend.cancelAdminMembership(item.id, { mode, reason: mode === 'period_end' ? '后台设置到期不续' : '后台立即关闭' })
      setMessage(mode === 'period_end' ? '已设置到期不续' : '已立即关闭会员')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '会员订阅操作失败')
    }
  }

  function openAdjustment(item: BackendMembershipSubscription) {
    setEditing(item)
    setAdjustTier(item.tier)
    setAdjustStatus(item.status)
    setAdjustStartsAt(toDateTimeInput(item.startsAt))
    setAdjustExpiresAt(toDateTimeInput(item.expiresAt))
    setAdjustReason('')
    setMessage('')
    setError('')
  }

  function openManager(item: BackendMembershipSubscription) {
    setManagerEditing(item)
    setManagerStaffId(item.customerManager?.staffAccountId || '')
    setManagerNote(item.customerManager?.note || '')
    setMessage('')
    setError('')
  }

  async function submitManager(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!managerEditing) return
    if (!managerStaffId) {
      setError('请选择客户经理')
      return
    }
    try {
      setSavingManager(true)
      setMessage('')
      setError('')
      await backend.assignMembershipManager(managerEditing.id, { staffAccountId: managerStaffId, note: managerNote.trim() })
      setMessage('客户经理已分配')
      setManagerEditing(null)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '客户经理分配失败')
    } finally {
      setSavingManager(false)
    }
  }

  async function submitAdjustment(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!editing) return
    if (!adjustReason.trim()) {
      setError('请填写调整原因')
      return
    }
    if (!window.confirm('确认保存会员订阅调整？等级、状态或有效期会影响用户当前会员权益。')) return
    try {
      setSavingAdjustment(true)
      setMessage('')
      setError('')
      await backend.updateAdminMembership(editing.id, {
        tier: adjustTier,
        status: adjustStatus,
        startsAt: new Date(adjustStartsAt).toISOString(),
        expiresAt: new Date(adjustExpiresAt).toISOString(),
        reason: adjustReason.trim(),
      })
      setMessage('会员订阅已调整，用户会员缓存已同步')
      setEditing(null)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '会员订阅调整失败')
    } finally {
      setSavingAdjustment(false)
    }
  }

  return (
    <AdminShell title="会员订阅" description={canUpdateMembership ? '处理会员订阅事实、手动赠送、到期校准和客户经理；不在这里做退款或通知派发。' : '查看会员订阅事实、有效期、来源和客户经理。'}>
      {(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="mb-4 border border-line bg-white">
        <div className="grid gap-3 border-b border-line px-4 py-3 lg:grid-cols-[1fr_auto] lg:items-center">
          <form className="grid gap-3 md:grid-cols-[1fr_150px_150px_auto]" onSubmit={(event) => { event.preventDefault(); void reload() }}>
            <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={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索姓名、手机号、通行证" className="h-10 w-full rounded-[4px] border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
            </div>
            <select value={tier} onChange={(event) => { setTier(event.target.value); void reload({ search, tier: event.target.value, status }) }} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              <option value="">全部等级</option>
              <option value="junior">初级会员</option>
              <option value="senior">高级会员</option>
            </select>
            <select value={status} onChange={(event) => { setStatus(event.target.value); void reload({ search, tier, status: event.target.value }) }} className="h-10 rounded-[4px] 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="past_due">扣款待处理</option>
              <option value="canceled">已取消</option>
            </select>
            <button className="h-10 rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white">查询</button>
          </form>
          {canUpdateMembership && (
            <div className="flex flex-wrap gap-2">
              <button type="button" onClick={() => void runJob('expire')} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                <TimerReset className="h-3.5 w-3.5" />
                到期处理
              </button>
              <Link href="/admin/membership/entitlements" className="inline-flex h-9 items-center rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                权益额度账户
              </Link>
            </div>
          )}
        </div>

        <div className="divide-y divide-line">
          {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) => (
            <div key={item.id} className="grid gap-4 px-5 py-4 xl:grid-cols-[1fr_160px_180px_140px] xl:items-center">
              <div>
                <div className="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 || '-'} · 手机 {item.userPhone || '-'}</div>
              </div>
              <div className="text-sm font-bold text-muted">
                <div>{tierLabel[item.tier] || item.tier}</div>
                <div className="mt-1 text-xs">{item.billingCycle === 'yearly' ? '年付' : item.billingCycle === 'monthly' ? '月付' : '手动赠送'}</div>
              </div>
              <div className="text-xs font-bold text-muted">
                <div>开始：{formatDate(item.startsAt)}</div>
                <div className="mt-1">到期：{formatDate(item.expiresAt)}</div>
                {item.paidAmountSnapshot ? <div className="mt-1">实付快照：¥{(item.paidAmountSnapshot / 100).toFixed(2)}</div> : null}
                {item.cancelRequestedAt ? <div className="mt-1 text-amber-700">取消申请：{formatDate(item.cancelRequestedAt)}</div> : null}
                {item.customerManager?.staffName ? <div className="mt-1">客户经理：{item.customerManager.staffName}</div> : null}
              </div>
              <div className="xl:text-right">
                <div className={`inline-flex rounded-[4px] px-2 py-1 text-xs font-extrabold ${item.status === 'active' ? 'bg-green-50 text-green' : item.status === 'expired' ? 'bg-red-50 text-red-700' : 'bg-bg text-muted'}`}>
                  {statusLabel[item.status] || item.status}
                </div>
                <div className="mt-2 text-xs font-bold text-muted">剩余 {item.daysLeft} 天 · 消息 {item.messageCount || 0}</div>
                {canUpdateMembership && (
                  <div className="mt-3 flex flex-wrap justify-start gap-2 xl:justify-end">
                    <button type="button" onClick={() => openAdjustment(item)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">调整订阅</button>
                    {item.tier === 'senior' && (
                      <button type="button" onClick={() => openManager(item)} className="h-8 rounded-[4px] border border-brand px-2 text-xs font-extrabold text-brand hover:bg-brand hover:text-white">
                        {item.customerManager?.staffName ? '更换客户经理' : '分配客户经理'}
                      </button>
                    )}
                    {item.status === 'active' && (
                      <>
                        <button type="button" onClick={() => void operateMembership(item, 'period_end')} className="h-8 rounded-[4px] border border-line px-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">到期不续</button>
                        <button type="button" onClick={() => void operateMembership(item, 'immediate')} className="h-8 rounded-[4px] border border-line px-2 text-xs font-extrabold text-muted hover:border-red-300 hover:text-red-700">立即关闭</button>
                      </>
                    )}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </section>

      {canUpdateMembership && editing && (
        <section className="mb-4 border border-line bg-white">
          <div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3">
            <div>
              <div className="flex items-center gap-2 text-sm font-extrabold text-ink">
                <PencilLine className="h-4 w-4 text-brand" />
                调整会员订阅
              </div>
              <div className="mt-1 text-xs font-bold text-muted">
                {editing.userName || editing.userPhone || editing.passportNo || editing.userId} · 调整等级、状态和有效期，原因会写入会员事件与后台审计。
              </div>
            </div>
            <button type="button" onClick={() => setEditing(null)} className="h-8 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">收起</button>
          </div>
          <form onSubmit={submitAdjustment} className="grid gap-3 p-4 xl:grid-cols-[140px_140px_210px_210px_1fr_auto] xl:items-end">
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              会员等级
              <select value={adjustTier} onChange={(event) => setAdjustTier(event.target.value as 'junior' | 'senior')} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand">
                <option value="junior">初级会员</option>
                <option value="senior">高级会员</option>
              </select>
            </label>
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              状态
              <select value={adjustStatus} onChange={(event) => setAdjustStatus(event.target.value as BackendMembershipSubscription['status'])} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand">
                <option value="active">有效</option>
                <option value="past_due">扣款待处理</option>
                <option value="expired">已到期</option>
                <option value="canceled">已取消</option>
                <option value="refunded">已关闭</option>
              </select>
            </label>
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              开始时间
              <input value={adjustStartsAt} onChange={(event) => setAdjustStartsAt(event.target.value)} type="datetime-local" required className="h-10 rounded-[4px] border border-line px-3 text-sm text-ink outline-none focus:border-brand" />
            </label>
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              到期时间
              <input value={adjustExpiresAt} onChange={(event) => setAdjustExpiresAt(event.target.value)} type="datetime-local" required className="h-10 rounded-[4px] border border-line px-3 text-sm text-ink outline-none focus:border-brand" />
            </label>
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              调整原因
              <input value={adjustReason} onChange={(event) => setAdjustReason(event.target.value)} required placeholder="例如：线下续费补录 / 有效期修正" className="h-10 rounded-[4px] border border-line px-3 text-sm text-ink outline-none focus:border-brand" />
            </label>
            <button disabled={savingAdjustment} className="h-10 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark disabled:bg-line-dark">{savingAdjustment ? '保存中...' : '保存调整'}</button>
          </form>
        </section>
      )}

      {canUpdateMembership && managerEditing && (
        <section className="mb-4 border border-line bg-white">
          <div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3">
            <div>
              <div className="text-sm font-extrabold text-ink">分配客户经理</div>
              <div className="mt-1 text-xs font-bold text-muted">
                {managerEditing.userName || managerEditing.userPhone || managerEditing.passportNo || managerEditing.userId} · 仅高级会员需要客户经理，保存后会结束旧分配并写入会员事件。
              </div>
            </div>
            <button type="button" onClick={() => setManagerEditing(null)} className="h-8 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">收起</button>
          </div>
          <form onSubmit={submitManager} className="grid gap-3 p-4 lg:grid-cols-[260px_1fr_auto] lg:items-end">
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              客户经理
              <select value={managerStaffId} onChange={(event) => setManagerStaffId(event.target.value)} required className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand">
                <option value="">请选择</option>
                {staff.map((item) => <option key={item.id} value={item.id}>{item.displayName || item.phone} · {item.roleName || item.role}</option>)}
              </select>
            </label>
            <label className="grid gap-1.5 text-xs font-extrabold text-muted">
              分配备注
              <input value={managerNote} onChange={(event) => setManagerNote(event.target.value)} placeholder="例如：机构客户专属对接 / 线下续费跟进" className="h-10 rounded-[4px] border border-line px-3 text-sm text-ink outline-none focus:border-brand" />
            </label>
            <button disabled={savingManager} className="h-10 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark disabled:bg-line-dark">{savingManager ? '保存中...' : '确认分配'}</button>
          </form>
        </section>
      )}

      <section className={`grid gap-4 ${canUpdateMembership ? 'lg:grid-cols-[360px_1fr]' : ''}`}>
        {canUpdateMembership && (
          <form onSubmit={submitGrant} className="border border-line bg-white p-4">
            <div className="mb-3 flex items-center gap-2 text-sm font-extrabold text-ink">
              <Gift className="h-4 w-4 text-brand" />
              手动赠送会员
            </div>
            <div className="space-y-3">
              <input value={grantUser} onChange={(event) => setGrantUser(event.target.value)} placeholder="用户 ID、通行证或手机号" className="h-10 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <div className="grid grid-cols-2 gap-3">
                <select value={grantTier} onChange={(event) => setGrantTier(event.target.value as 'junior' | 'senior')} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
                  <option value="junior">初级会员</option>
                  <option value="senior">高级会员</option>
                </select>
                <input value={grantDays} onChange={(event) => setGrantDays(event.target.value)} type="number" min="1" max="3660" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              </div>
              <button className="h-10 w-full rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark">确认赠送</button>
            </div>
          </form>
        )}

        <div className="border border-line bg-white p-4">
          <div className="text-sm font-extrabold text-ink">会员运营边界</div>
          <div className="mt-3 grid gap-2 text-sm font-bold leading-6 text-muted">
            <p>会员等级以订阅记录为事实源，用户档案页只读展示会员状态。</p>
            <p>订阅等级、状态和有效期在本页调整；智能体次数这类可计数权益，在“权益额度账户”查看和修正。</p>
            <p>本轮不展示退款、通知生成和消息派发入口。</p>
          </div>
        </div>
      </section>
    </AdminShell>
  )
}
