'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendMembershipPlan } from '@/lib/backend'

const emptyPlan = {
  level: 'junior',
  name: '',
  badge: '',
  description: '',
  ctaLabel: '',
  tone: 'brand',
  monthlyPriceAmount: 9900,
  yearlyPriceAmount: 99800,
  recommended: false,
  sortOrder: 10,
  status: 'draft',
  productStatus: 'draft',
}

export function MembershipPlanForm({ productId }: { productId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState(emptyPlan)
  const [error, setError] = useState('')

  function toSafeNumber(value: unknown) {
    const num = Number(value)
    if (!Number.isFinite(num)) return 0
    return Math.max(0, Math.round(num))
  }

  function displayYuan(value: unknown) {
    return (toSafeNumber(value) / 100).toFixed(2).replace(/\.00$/, '')
  }

  useEffect(() => {
    if (!productId) return
    void backend.adminMembershipPlans().then((result) => {
      const current = result.items.find((item) => item.productId === productId)
      if (current) {
        setForm({
          level: current.level,
          name: current.name,
          badge: current.badge,
          description: current.description,
          ctaLabel: current.ctaLabel,
          tone: current.tone,
          monthlyPriceAmount: toSafeNumber(current.monthlyPriceAmount),
          yearlyPriceAmount: toSafeNumber(current.yearlyPriceAmount),
          recommended: current.recommended,
          sortOrder: toSafeNumber(current.sortOrder),
          status: current.status,
          productStatus: current.status,
        })
      }
    }).catch((err) => setError(err instanceof Error ? err.message : '会员方案加载失败'))
  }, [productId])

  return (
    <AdminShell title="维护会员方案" description="会员只维护现有初级会员和高级会员，不在这里新增新等级。保存后用户端会员页和结算页同步生效。">
      <form
        className="border border-line bg-white"
        onSubmit={async (event) => {
          event.preventDefault()
          try {
            await backend.saveAdminMembershipPlan(productId || null, {
              ...form,
              monthlyPriceAmount: toSafeNumber(form.monthlyPriceAmount),
              yearlyPriceAmount: toSafeNumber(form.yearlyPriceAmount),
              sortOrder: toSafeNumber(form.sortOrder),
            } as Partial<BackendMembershipPlan>)
            router.push('/admin/products/membership')
          } catch (err) {
            setError(err instanceof Error ? err.message : '保存失败')
          }
        }}
      >
        <div className="grid gap-4 border-b border-line px-5 py-4 lg:grid-cols-[1fr_auto] lg:items-center">
          <div>
            <div className="text-base font-extrabold text-ink">{form.name || '会员方案'}</div>
            <div className="mt-1 text-xs font-bold text-muted">当前正在维护 {productId || '现有会员方案'} 的展示、价格、排序与状态。</div>
          </div>
          <button className="h-9 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark">保存修改</button>
        </div>
        {error && <div className="mx-5 mt-4 border border-red-100 bg-red-50 px-3 py-2 text-sm font-bold text-red-700">{error}</div>}

        <div className="grid gap-0 lg:grid-cols-[minmax(0,1fr)_360px]">
          <section className="space-y-5 px-5 py-5">
            <div>
              <div className="mb-3 text-sm font-extrabold text-ink">基础展示</div>
              <div className="grid gap-4 md:grid-cols-2">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">会员等级</span>
                  <select value={form.level} onChange={(event) => setForm((current) => ({ ...current, level: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                    <option value="junior">初级会员</option>
                    <option value="senior">高级会员</option>
                  </select>
                  <span className="mt-1 block text-xs font-bold text-soft">决定用户购买后开通的会员等级。</span>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">方案名称</span>
                  <input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} required className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                  <span className="mt-1 block text-xs font-bold text-soft">显示在会员页卡片标题和订单标题中。</span>
                </label>
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">角标文案</span>
                <input value={form.badge} onChange={(event) => setForm((current) => ({ ...current, badge: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                <span className="mt-1 block text-xs font-bold text-soft">例如“推荐”“高级”，显示在会员卡片顶部。</span>
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">视觉风格</span>
                <select value={form.tone} onChange={(event) => setForm((current) => ({ ...current, tone: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                  <option value="brand">初级会员样式</option>
                  <option value="gold">高级会员样式</option>
                </select>
                <span className="mt-1 block text-xs font-bold text-soft">控制用户端会员卡片的强调色。</span>
              </label>
            </div>

            <label className="block">
              <span className="mb-2 block text-sm font-bold text-ink">方案介绍</span>
              <textarea value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} required rows={4} className="w-full rounded-[4px] border border-line p-3 text-sm" />
              <span className="mt-1 block text-xs font-bold text-soft">显示在会员页价格卡片里，说明适合什么用户。</span>
            </label>

            <div className="grid gap-4 md:grid-cols-3">
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">月付价格（元）</span>
                <input
                  value={displayYuan(form.monthlyPriceAmount)}
                  onChange={(event) => setForm((current) => ({ ...current, monthlyPriceAmount: toSafeNumber(event.target.value) * 100 }))}
                  type="number"
                  min="0"
                  className="h-10 w-full rounded-[4px] border border-line px-3 text-sm"
                />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">年付价格（元）</span>
                <input
                  value={displayYuan(form.yearlyPriceAmount)}
                  onChange={(event) => setForm((current) => ({ ...current, yearlyPriceAmount: toSafeNumber(event.target.value) * 100 }))}
                  type="number"
                  min="0"
                  className="h-10 w-full rounded-[4px] border border-line px-3 text-sm"
                />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">按钮文案</span>
                <input value={form.ctaLabel} onChange={(event) => setForm((current) => ({ ...current, ctaLabel: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              </label>
            </div>
          </section>

          <aside className="border-t border-line bg-bg/60 px-5 py-5 lg:border-l lg:border-t-0">
            <div className="mb-3 text-sm font-extrabold text-ink">发布控制</div>
            <div className="space-y-4">
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">排序</span>
                <input value={form.sortOrder} onChange={(event) => setForm((current) => ({ ...current, sortOrder: Number(event.target.value || 0) }))} type="number" className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                <span className="mt-1 block text-xs font-bold text-soft">数字越小越靠前。</span>
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">发布状态</span>
                <select value={form.status} onChange={(event) => setForm((current) => ({ ...current, status: event.target.value, productStatus: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                  <option value="draft">草稿</option>
                  <option value="published">已发布</option>
                  <option value="offline">已下架</option>
                </select>
                <span className="mt-1 block text-xs font-bold text-soft">只有已发布状态会在用户端展示和结算。</span>
              </label>
              <label className="flex items-center gap-2 rounded-[4px] border border-line bg-white px-3 py-2 text-sm font-bold text-muted">
                <input type="checkbox" checked={form.recommended} onChange={(event) => setForm((current) => ({ ...current, recommended: event.target.checked }))} />
                设为推荐方案
              </label>
            </div>
          </aside>
        </div>
      </form>
    </AdminShell>
  )
}
