'use client'

import { useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { Database, FileText, Gift, Save, Search, SlidersHorizontal, Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import {
  apiBase,
  backend,
  type BackendMembershipBenefit,
  type BackendMembershipCatalog,
  type BackendMembershipContentDelivery,
  type BackendMembershipEntitlementAccount,
  type BackendMembershipPlanBenefit,
} from '@/lib/backend'

type BenefitForm = {
  code: string
  label: string
  groupKey: string
  benefitType: string
  targetType: string
  targetRef: string
  executionMode: string
  status: string
  sortOrder: string
  description: string
  defaultValueText: string
}

type ContentForm = {
  id: string
  title: string
  contentType: string
  eligibleTiers: string
  fileId: string
  href: string
  periodKey: string
  status: string
}

const emptyBenefitForm: BenefitForm = {
  code: '',
  label: '',
  groupKey: 'general',
  benefitType: 'display',
  targetType: 'global',
  targetRef: '',
  executionMode: 'display',
  status: 'active',
  sortOrder: '100',
  description: '',
  defaultValueText: '{}',
}

const emptyContentForm: ContentForm = {
  id: '',
  title: '',
  contentType: 'monthly_report',
  eligibleTiers: 'junior,senior',
  fileId: '',
  href: '',
  periodKey: new Date().toISOString().slice(0, 7),
  status: 'draft',
}

function parseJsonObject(text: string) {
  const parsed = JSON.parse(text || '{}')
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('JSON 必须是对象')
  return parsed as Record<string, unknown>
}

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

function absoluteApiUrl(path: string) {
  if (!path || /^https?:\/\//.test(path) || path.startsWith('data:')) return path
  return `${apiBase.replace(/\/api$/, '')}${path}`
}

function formatJsonSummary(value?: Record<string, unknown>) {
  const text = JSON.stringify(value || {})
  return text.length > 120 ? `${text.slice(0, 120)}...` : text
}

function benefitToForm(item: BackendMembershipBenefit): BenefitForm {
  return {
    code: item.code,
    label: item.label,
    groupKey: item.groupKey || 'general',
    benefitType: item.benefitType || 'display',
    targetType: item.targetType || 'global',
    targetRef: item.targetRef || '',
    executionMode: item.executionMode || 'display',
    status: item.status || 'active',
    sortOrder: String(item.sortOrder ?? 100),
    description: item.description || '',
    defaultValueText: JSON.stringify(item.defaultValue || {}, null, 2),
  }
}

function contentToForm(item: BackendMembershipContentDelivery): ContentForm {
  return {
    id: item.id,
    title: item.title,
    contentType: item.contentType || 'monthly_report',
    eligibleTiers: (item.eligibleTiers || []).join(','),
    fileId: item.fileId || '',
    href: item.href || '',
    periodKey: item.periodKey || new Date().toISOString().slice(0, 7),
    status: item.status || 'draft',
  }
}

export default function AdminMembershipBenefitsPage() {
  const [catalog, setCatalog] = useState<BackendMembershipCatalog | null>(null)
  const [benefits, setBenefits] = useState<BackendMembershipBenefit[]>([])
  const [planDrafts, setPlanDrafts] = useState<Record<string, BackendMembershipPlanBenefit[]>>({})
  const [entitlements, setEntitlements] = useState<BackendMembershipEntitlementAccount[]>([])
  const [contents, setContents] = useState<BackendMembershipContentDelivery[]>([])
  const [benefitForm, setBenefitForm] = useState<BenefitForm>(emptyBenefitForm)
  const [contentForm, setContentForm] = useState<ContentForm>(emptyContentForm)
  const [entitlementSearch, setEntitlementSearch] = useState('')
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  const benefitMap = useMemo(() => new Map(benefits.map((item) => [item.code, item])), [benefits])

  async function reload() {
    setLoading(true)
    try {
      const [nextCatalog, benefitResult, entitlementResult, contentResult] = await Promise.all([
        backend.adminMembershipCatalog(),
        backend.adminMembershipBenefits(),
        backend.adminMembershipEntitlements({ search: entitlementSearch }),
        backend.adminMembershipContentDeliveries(),
      ])
      setCatalog(nextCatalog)
      setBenefits(benefitResult.items)
      setPlanDrafts(nextCatalog.planBenefits || {})
      setEntitlements(entitlementResult.items)
      setContents(contentResult.items)
      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 saveBenefit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    try {
      const defaultValue = parseJsonObject(benefitForm.defaultValueText)
      const saved = await backend.saveAdminMembershipBenefit(benefitForm.code || null, {
        code: benefitForm.code,
        label: benefitForm.label,
        groupKey: benefitForm.groupKey,
        benefitType: benefitForm.benefitType,
        targetType: benefitForm.targetType,
        targetRef: benefitForm.targetRef,
        executionMode: benefitForm.executionMode,
        status: benefitForm.status,
        sortOrder: Number(benefitForm.sortOrder || 100),
        description: benefitForm.description,
        defaultValue,
      })
      setMessage(`权益已保存：${saved.label}`)
      setBenefitForm(emptyBenefitForm)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '权益保存失败')
    }
  }

  function setPlanBenefit(productId: string, benefit: BackendMembershipBenefit, patch: Partial<BackendMembershipPlanBenefit>) {
    setPlanDrafts((prev) => {
      const current = [...(prev[productId] || [])]
      const index = current.findIndex((item) => item.benefitCode === benefit.code)
      const base: BackendMembershipPlanBenefit = index >= 0
        ? current[index]
        : {
            benefitCode: benefit.code,
            enabled: false,
            value: benefit.defaultValue || {},
            displayLabel: benefit.label,
            sortOrder: benefit.sortOrder || 100,
            status: 'active',
          }
      const next = { ...base, ...patch }
      if (index >= 0) current[index] = next
      else current.push(next)
      return { ...prev, [productId]: current.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0)) }
    })
  }

  async function savePlanBenefits(productId: string) {
    try {
      const saved = await backend.saveAdminMembershipPlanBenefits(productId, planDrafts[productId] || [])
      setMessage(`方案权益已保存：${saved.productId}`)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '方案权益保存失败')
    }
  }

  async function adjustEntitlement(item: BackendMembershipEntitlementAccount, delta: number) {
    try {
      await backend.adjustAdminMembershipEntitlement(item.id, { delta, note: delta > 0 ? '后台补充额度' : '后台扣减额度' })
      setMessage('额度已调整并写入流水')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '额度调整失败')
    }
  }

  async function saveContent(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    try {
      const saved = await backend.saveAdminMembershipContentDelivery(contentForm.id || null, {
        title: contentForm.title,
        contentType: contentForm.contentType,
        eligibleTiers: contentForm.eligibleTiers.split(/[,\n，；;]+/).map((item) => item.trim()).filter(Boolean),
        fileId: contentForm.fileId || undefined,
        href: contentForm.href,
        periodKey: contentForm.periodKey,
        status: contentForm.status,
      })
      setMessage(`会员内容已保存：${saved.title}`)
      setContentForm(emptyContentForm)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '会员内容保存失败')
    }
  }

  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>
      )}

      <div className="grid gap-4 xl:grid-cols-[420px_1fr]">
        <form onSubmit={saveBenefit} 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="grid gap-3">
            <input value={benefitForm.code} onChange={(event) => setBenefitForm({ ...benefitForm, code: event.target.value })} placeholder="权益编码，如 agent_monthly_quota" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
            <input value={benefitForm.label} onChange={(event) => setBenefitForm({ ...benefitForm, label: event.target.value })} placeholder="权益名称" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
            <div className="grid grid-cols-2 gap-3">
              <input value={benefitForm.groupKey} onChange={(event) => setBenefitForm({ ...benefitForm, groupKey: event.target.value })} placeholder="分组" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <select value={benefitForm.executionMode} onChange={(event) => setBenefitForm({ ...benefitForm, executionMode: event.target.value })} className="h-10 rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
                <option value="display">展示</option>
                <option value="automatic">自动执行</option>
                <option value="manual_quote">人工报价提示</option>
                <option value="ledger">额度流水</option>
                <option value="manual_assignment">人工分配</option>
              </select>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <input value={benefitForm.benefitType} onChange={(event) => setBenefitForm({ ...benefitForm, benefitType: event.target.value })} placeholder="权益类型" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={benefitForm.targetType} onChange={(event) => setBenefitForm({ ...benefitForm, targetType: event.target.value })} placeholder="目标类型" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
            </div>
            <input value={benefitForm.targetRef} onChange={(event) => setBenefitForm({ ...benefitForm, targetRef: event.target.value })} placeholder="目标引用，可空" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
            <textarea value={benefitForm.defaultValueText} onChange={(event) => setBenefitForm({ ...benefitForm, defaultValueText: event.target.value })} rows={4} className="rounded-[4px] border border-line px-3 py-2 font-mono text-xs outline-none focus:border-brand" />
            <div className="grid grid-cols-2 gap-3">
              <input value={benefitForm.sortOrder} onChange={(event) => setBenefitForm({ ...benefitForm, sortOrder: event.target.value })} type="number" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <select value={benefitForm.status} onChange={(event) => setBenefitForm({ ...benefitForm, 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="active">启用</option>
                <option value="inactive">停用</option>
                <option value="draft">草稿</option>
              </select>
            </div>
            <textarea value={benefitForm.description} onChange={(event) => setBenefitForm({ ...benefitForm, description: event.target.value })} placeholder="说明" rows={3} className="rounded-[4px] border border-line px-3 py-2 text-sm outline-none focus:border-brand" />
            <button className="inline-flex h-10 items-center justify-center gap-2 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark">
              <Save className="h-4 w-4" />
              保存权益
            </button>
          </div>
        </form>

        <section className="border border-line bg-white">
          <div className="flex items-center justify-between border-b border-line px-4 py-3">
            <div className="flex items-center gap-2 text-sm font-extrabold text-ink">
              <SlidersHorizontal className="h-4 w-4 text-brand" />
              方案权益
            </div>
            {loading && <span className="text-xs font-bold text-muted">正在加载...</span>}
          </div>
          <div className="divide-y divide-line">
            {benefits.map((item) => (
              <button key={item.code} type="button" onClick={() => setBenefitForm(benefitToForm(item))} className="grid w-full gap-1 px-4 py-3 text-left hover:bg-bg md:grid-cols-[180px_1fr_120px]">
                <div className="font-mono text-xs font-bold text-muted">{item.code}</div>
                <div>
                  <div className="text-sm font-extrabold text-ink">{item.label}</div>
                  <div className="mt-1 text-xs font-bold text-muted">{item.groupKey} · {item.executionMode}</div>
                </div>
                <div className="text-xs font-bold text-muted md:text-right">{item.status}</div>
              </button>
            ))}
          </div>
          <div className="grid gap-4 border-t border-line p-4 lg:grid-cols-2">
            {(catalog?.plans || []).map((plan) => {
              const rows = benefits.map((benefit) => {
                const existing = (planDrafts[plan.productId] || []).find((item) => item.benefitCode === benefit.code)
                return { benefit, existing }
              })
              return (
                <div key={plan.productId} className="border border-line">
                  <div className="flex items-center justify-between border-b border-line px-3 py-2">
                    <div className="text-sm font-extrabold text-ink">{plan.name}</div>
                    <button type="button" onClick={() => void savePlanBenefits(plan.productId)} className="h-8 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">保存</button>
                  </div>
                  <div className="max-h-[360px] overflow-auto">
                    {rows.map(({ benefit, existing }) => (
                      <label key={`${plan.productId}-${benefit.code}`} className="grid gap-2 border-b border-line px-3 py-2 text-xs md:grid-cols-[20px_1fr]">
                        <input checked={Boolean(existing?.enabled)} onChange={(event) => setPlanBenefit(plan.productId, benefit, { enabled: event.target.checked })} type="checkbox" className="mt-1 h-4 w-4 accent-brand" />
                          <span>
                            <span className="block font-extrabold text-ink">{benefit.label}</span>
                            <input value={existing?.displayLabel ?? benefit.label} onChange={(event) => setPlanBenefit(plan.productId, benefit, { displayLabel: event.target.value })} className="mt-2 h-8 w-full rounded-[4px] border border-line px-2 text-xs outline-none focus:border-brand" />
                            <span className="mt-2 block rounded-[4px] border border-line bg-bg px-2 py-1 font-mono text-[11px] font-bold leading-5 text-muted">
                              value_json: {formatJsonSummary(existing?.value || benefit.defaultValue)}
                            </span>
                          </span>
                        </label>
                      ))}
                  </div>
                </div>
              )
            })}
          </div>
        </section>
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-[1fr_420px]">
        <section className="border border-line bg-white">
          <div className="grid gap-3 border-b border-line px-4 py-3 md:grid-cols-[1fr_auto] md:items-center">
            <div className="flex items-center gap-2 text-sm font-extrabold text-ink">
              <Database className="h-4 w-4 text-brand" />
              额度账户
            </div>
            <form className="flex gap-2" 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={entitlementSearch} onChange={(event) => setEntitlementSearch(event.target.value)} placeholder="搜索用户" className="h-9 w-56 rounded-[4px] border border-line pl-9 pr-3 text-sm outline-none focus:border-brand" />
              </div>
              <button className="h-9 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">查询</button>
            </form>
          </div>
          <div className="divide-y divide-line">
            {entitlements.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无额度账户</div>}
            {entitlements.map((item) => (
              <div key={item.id} className="grid gap-3 px-4 py-3 lg:grid-cols-[1fr_150px_150px] lg: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">{benefitMap.get(item.benefitCode)?.label || item.benefitCode} · {item.periodKey}</div>
                </div>
                <div className="text-sm font-bold text-muted">剩余 {item.quotaRemaining} / {item.quotaTotal}</div>
                <div className="flex gap-2 lg:justify-end">
                  <button type="button" onClick={() => void adjustEntitlement(item, 1)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">+1</button>
                  <button type="button" onClick={() => void adjustEntitlement(item, -1)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-extrabold text-ink hover:border-red-300 hover:text-red-700">-1</button>
                </div>
              </div>
            ))}
          </div>
        </section>

        <section className="border border-line bg-white">
          <form onSubmit={saveContent} className="border-b border-line p-4">
            <div className="mb-3 flex items-center gap-2 text-sm font-extrabold text-ink">
              <FileText className="h-4 w-4 text-brand" />
              会员内容
            </div>
            <div className="grid gap-3">
              <input value={contentForm.title} onChange={(event) => setContentForm({ ...contentForm, title: event.target.value })} placeholder="报告标题" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <div className="grid grid-cols-2 gap-3">
                <input value={contentForm.periodKey} onChange={(event) => setContentForm({ ...contentForm, periodKey: event.target.value })} placeholder="2026-06" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
                <select value={contentForm.status} onChange={(event) => setContentForm({ ...contentForm, 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="draft">草稿</option>
                  <option value="published">发布</option>
                  <option value="offline">下线</option>
                </select>
              </div>
              <input value={contentForm.eligibleTiers} onChange={(event) => setContentForm({ ...contentForm, eligibleTiers: event.target.value })} placeholder="junior,senior" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <label className="grid gap-2 rounded-[4px] border border-line bg-bg px-3 py-2 text-xs font-bold text-muted">
                <span>报告文件</span>
                <span className="font-mono text-[11px] text-soft">{contentForm.fileId ? `fileId: ${contentForm.fileId}` : '未选择文件，报告发布前必须上传'}</span>
                <span className="inline-flex h-8 w-fit cursor-pointer items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                  <Upload className="h-3.5 w-3.5" />
                  上传或替换文件
                  <input
                    type="file"
                    className="sr-only"
                    onChange={async (event) => {
                      const file = event.target.files?.[0]
                      if (!file) return
                      try {
                        const uploaded = await backend.uploadAdminFile(file)
                        setContentForm((current) => ({ ...current, fileId: uploaded.id, href: absoluteApiUrl(uploaded.url) }))
                        setMessage(`文件已上传：${uploaded.fileName}`)
                        setError('')
                      } catch (err) {
                        setError(err instanceof Error ? err.message : '会员内容文件上传失败')
                      } finally {
                        event.target.value = ''
                      }
                    }}
                  />
                </span>
              </label>
              <input value={contentForm.href} onChange={(event) => setContentForm({ ...contentForm, href: event.target.value })} placeholder="页面地址（选填，不作为文件交付）" className="h-10 rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <button className="h-10 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark">保存内容</button>
            </div>
          </form>
          <div className="divide-y divide-line">
            {contents.map((item) => (
              <button key={item.id} type="button" onClick={() => setContentForm(contentToForm(item))} className="w-full px-4 py-3 text-left hover:bg-bg">
                <div className="font-extrabold text-ink">{item.title}</div>
                <div className="mt-1 text-xs font-bold text-muted">{item.periodKey} · {item.status} · {formatDate(item.publishedAt)}</div>
              </button>
            ))}
          </div>
        </section>
      </div>
    </AdminShell>
  )
}
