'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, cents, type BackendCheckoutPreview, type BackendCoupon, type BackendProduct, yuan } from '@/lib/backend'

const productTypeOptions = [
  { label: '会员', value: 'membership' },
  { label: '课程', value: 'course' },
  { label: '活动', value: 'event' },
  { label: '数据', value: 'data' },
  { label: '智能体', value: 'agent' },
  { label: '专家咨询', value: 'expert' },
] as const

const membershipOptions = [
  { label: '注册用户', value: 'registered' },
  { label: '初级会员', value: 'junior' },
  { label: '高级会员', value: 'senior' },
] as const

type CouponFormState = {
  code: string
  name: string
  description: string
  discountType: BackendCoupon['discountType']
  discountValue: string
  maxDiscountAmount: string
  minOrderAmount: string
  totalQuantity: string
  budgetAmount: string
  startsAt: string
  endsAt: string
  status: BackendCoupon['status']
  productScopeMode: 'all' | 'include'
  productTypes: string[]
  productIds: string[]
  excludeProductIds: string[]
  membershipLevels: Array<'registered' | 'junior' | 'senior'>
  passportNos: string
  userIds: string
  firstOrderOnly: boolean
  newUserOnly: boolean
  perUser: string
  perDay: string
  allowMemberDiscount: boolean
}

const emptyForm: CouponFormState = {
  code: '',
  name: '',
  description: '',
  discountType: 'amount',
  discountValue: '100',
  maxDiscountAmount: '',
  minOrderAmount: '0',
  totalQuantity: '100',
  budgetAmount: '',
  startsAt: toInputDate(new Date().toISOString()),
  endsAt: toInputDate(new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString()),
  status: 'active',
  productScopeMode: 'all',
  productTypes: [],
  productIds: [],
  excludeProductIds: [],
  membershipLevels: [],
  passportNos: '',
  userIds: '',
  firstOrderOnly: false,
  newUserOnly: false,
  perUser: '0',
  perDay: '0',
  allowMemberDiscount: true,
}

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

function toIsoDate(value: string) {
  return value ? new Date(value).toISOString() : null
}

function yuanString(value?: number | null) {
  if (!value) return ''
  return String(yuan(value))
}

function integerString(value?: number | null, fallback = '0') {
  return value === null || value === undefined ? fallback : String(value)
}

function splitLines(value: string) {
  return value.split(/[,\n，；;]+/).map((item) => item.trim()).filter(Boolean)
}

function formFromCoupon(coupon: BackendCoupon): CouponFormState {
  return {
    code: coupon.code || '',
    name: coupon.name || '',
    description: coupon.description || '',
    discountType: coupon.discountType || 'amount',
    discountValue: coupon.discountType === 'percent' ? String(coupon.discountValue || 0) : String(yuan(coupon.discountValue || 0)),
    maxDiscountAmount: yuanString(coupon.maxDiscountAmount),
    minOrderAmount: String(yuan(coupon.minOrderAmount || 0)),
    totalQuantity: String(coupon.totalQuantity || 0),
    budgetAmount: yuanString(coupon.budgetAmount),
    startsAt: toInputDate(coupon.startsAt),
    endsAt: toInputDate(coupon.endsAt),
    status: coupon.status || 'active',
    productScopeMode: coupon.productScope?.mode === 'include' ? 'include' : 'all',
    productTypes: coupon.productScope?.productTypes || [],
    productIds: coupon.productScope?.productIds || [],
    excludeProductIds: coupon.productScope?.excludeProductIds || [],
    membershipLevels: coupon.userScope?.membershipLevels || [],
    passportNos: (coupon.userScope?.passportNos || []).join('\n'),
    userIds: (coupon.userScope?.userIds || []).join('\n'),
    firstOrderOnly: Boolean(coupon.userScope?.firstOrderOnly),
    newUserOnly: Boolean(coupon.userScope?.newUserOnly),
    perUser: integerString(coupon.usageLimits?.perUser),
    perDay: integerString(coupon.usageLimits?.perDay),
    allowMemberDiscount: coupon.stackingPolicy?.allowMemberDiscount !== false,
  }
}

function toggleValue<T extends string>(values: T[], value: T, limit = Number.MAX_SAFE_INTEGER) {
  if (values.includes(value)) return values.filter((item) => item !== value)
  if (values.length >= limit) return values
  return [...values, value]
}

function buildPayload(form: CouponFormState) {
  return {
    code: form.code.trim().toUpperCase(),
    name: form.name.trim(),
    description: form.description.trim(),
    discountType: form.discountType,
    discountValue: form.discountType === 'percent'
      ? Math.round(Number(form.discountValue || 0))
      : cents(Number(form.discountValue || 0)),
    maxDiscountAmount: form.maxDiscountAmount ? cents(Number(form.maxDiscountAmount || 0)) : null,
    minOrderAmount: cents(Number(form.minOrderAmount || 0)),
    totalQuantity: Math.max(1, Math.round(Number(form.totalQuantity || 1))),
    budgetAmount: form.budgetAmount ? cents(Number(form.budgetAmount || 0)) : null,
    startsAt: toIsoDate(form.startsAt) || new Date().toISOString(),
    endsAt: toIsoDate(form.endsAt),
    status: form.status,
    productScope: {
      mode: form.productScopeMode,
      productTypes: form.productTypes,
      productIds: form.productIds,
      excludeProductIds: form.excludeProductIds,
    },
    userScope: {
      membershipLevels: form.membershipLevels,
      passportNos: splitLines(form.passportNos),
      userIds: splitLines(form.userIds),
      firstOrderOnly: form.firstOrderOnly,
      newUserOnly: form.newUserOnly,
    },
    usageLimits: {
      perUser: Math.max(0, Math.round(Number(form.perUser || 0))),
      perDay: Math.max(0, Math.round(Number(form.perDay || 0))),
    },
    stackingPolicy: {
      allowMemberDiscount: form.allowMemberDiscount,
    },
  }
}

function FieldHelp({ children }: { children: string }) {
  return <span className="mt-1 block text-xs font-bold text-soft">{children}</span>
}

export function CouponForm({ couponId }: { couponId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState<CouponFormState>(emptyForm)
  const [products, setProducts] = useState<BackendProduct[]>([])
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)
  const [loading, setLoading] = useState(Boolean(couponId))
  const [previewProductId, setPreviewProductId] = useState('')
  const [previewQuantity, setPreviewQuantity] = useState('1')
  const [previewMembershipLevel, setPreviewMembershipLevel] = useState<'registered' | 'junior' | 'senior'>('registered')
  const [previewPassportNo, setPreviewPassportNo] = useState('')
  const [preview, setPreview] = useState<BackendCheckoutPreview | null>(null)
  const [previewError, setPreviewError] = useState('')

  useEffect(() => {
    let cancelled = false
    async function load() {
      try {
        const [productResult, coupon] = await Promise.all([
          backend.adminProducts({ includeServiceTypes: true }),
          couponId ? backend.adminCoupon(couponId) : Promise.resolve(null),
        ])
        if (cancelled) return
        setProducts(productResult.items)
        setPreviewProductId(productResult.items[0]?.id || '')
        if (coupon) setForm(formFromCoupon(coupon))
        setError('')
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : '优惠码加载失败')
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    void load()
    return () => { cancelled = true }
  }, [couponId])

  const selectedPreviewProduct = useMemo(() => products.find((item) => item.id === previewProductId), [previewProductId, products])

  async function saveCoupon(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setSaving(true)
    setError('')
    try {
      await backend.saveAdminCoupon(couponId || null, buildPayload(form))
      router.push('/admin/coupons')
    } catch (err) {
      setError(err instanceof Error ? err.message : '优惠码保存失败')
    } finally {
      setSaving(false)
    }
  }

  async function runPreview() {
    if (!previewProductId) {
      setPreviewError('请选择用于试算的商品')
      return
    }
    setPreview(null)
    setPreviewError('')
    try {
      const result = await backend.previewAdminCoupon({
        couponId,
        coupon: buildPayload(form),
        membershipLevel: previewMembershipLevel,
        passportNo: previewPassportNo.trim(),
        items: [{ productId: previewProductId, quantity: Math.max(1, Math.round(Number(previewQuantity || 1))) }],
      })
      setPreview(result)
    } catch (err) {
      setPreviewError(err instanceof Error ? err.message : '优惠码试算失败')
    }
  }

  return (
    <AdminShell title={couponId ? '编辑优惠码' : '新增优惠码'} description="维护优惠方式、适用范围、用户限制、使用上限、预算和叠加规则。">
      <div className="mb-3 flex items-center justify-between">
        <Link href="/admin/coupons" className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-3.5 w-3.5" />
          返回优惠码列表
        </Link>
        {couponId && <Link href={`/admin/coupons/${couponId}/redemptions`} className="text-xs font-extrabold text-brand">使用记录</Link>}
      </div>

      <form className="border border-line bg-white" onSubmit={saveCoupon}>
        <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.code || (couponId ? '编辑优惠码' : '新增优惠码')}</div>
            <div className="mt-1 text-xs font-bold text-muted">{form.name || '配置优惠规则'}</div>
          </div>
          <button disabled={saving || loading} className="h-9 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
            {saving ? '保存中...' : '保存优惠码'}
          </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>}
        {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载优惠码...</div>}

        {!loading && (
          <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_360px]">
            <section className="space-y-6 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 xl:grid-cols-3">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">优惠码</span>
                    <input required value={form.code} onChange={(event) => setForm((current) => ({ ...current, code: event.target.value.toUpperCase() }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold uppercase" placeholder="DLBDI100" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">名称</span>
                    <input required value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} 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>
                    <select value={form.status} onChange={(event) => setForm((current) => ({ ...current, status: event.target.value as BackendCoupon['status'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                      <option value="active">启用</option>
                      <option value="paused">暂停</option>
                      <option value="expired">过期</option>
                    </select>
                  </label>
                  <label className="block md:col-span-2 xl:col-span-3">
                    <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 }))} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">开始时间</span>
                    <input type="datetime-local" value={form.startsAt} onChange={(event) => setForm((current) => ({ ...current, startsAt: event.target.value }))} 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 type="datetime-local" value={form.endsAt} onChange={(event) => setForm((current) => ({ ...current, endsAt: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                    <FieldHelp>留空表示长期有效。</FieldHelp>
                  </label>
                </div>
              </div>

              <div>
                <div className="mb-3 text-sm font-extrabold text-ink">优惠方式</div>
                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">类型</span>
                    <select value={form.discountType} onChange={(event) => setForm((current) => ({ ...current, discountType: event.target.value as BackendCoupon['discountType'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                      <option value="amount">固定金额减免</option>
                      <option value="percent">百分比折扣</option>
                    </select>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">{form.discountType === 'percent' ? '折扣比例（%）' : '减免金额（元）'}</span>
                    <input required type="number" min="0" step={form.discountType === 'percent' ? '1' : '0.01'} value={form.discountValue} onChange={(event) => setForm((current) => ({ ...current, discountValue: event.target.value }))} 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 type="number" min="0" step="0.01" value={form.maxDiscountAmount} onChange={(event) => setForm((current) => ({ ...current, maxDiscountAmount: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                    <FieldHelp>固定金额券可留空。</FieldHelp>
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">使用门槛（元）</span>
                    <input type="number" min="0" step="0.01" value={form.minOrderAmount} onChange={(event) => setForm((current) => ({ ...current, minOrderAmount: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                  </label>
                </div>
              </div>

              <div>
                <div className="mb-3 text-sm font-extrabold text-ink">适用范围</div>
                <div className="space-y-4">
                  <label className="block max-w-xs">
                    <span className="mb-2 block text-sm font-bold text-ink">商品范围</span>
                    <select value={form.productScopeMode} onChange={(event) => setForm((current) => ({ ...current, productScopeMode: event.target.value as 'all' | 'include' }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                      <option value="all">全站商品</option>
                      <option value="include">指定类型或商品</option>
                    </select>
                  </label>
                  <div className="grid gap-2 md:grid-cols-3">
                    {productTypeOptions.map((item) => {
                      const active = form.productTypes.includes(item.value)
                      return (
                        <button key={item.value} type="button" onClick={() => setForm((current) => ({ ...current, productTypes: toggleValue(current.productTypes, item.value) }))} className={`h-9 rounded-[4px] border px-3 text-xs font-extrabold ${active ? 'border-brand bg-brand-light text-brand' : 'border-line text-muted hover:border-brand hover:text-brand'}`}>{item.label}</button>
                      )
                    })}
                  </div>
                  <div className="grid gap-4 lg:grid-cols-2">
                    <label className="block">
                      <span className="mb-2 block text-sm font-bold text-ink">指定商品</span>
                      <select multiple value={form.productIds} onChange={(event) => setForm((current) => ({ ...current, productIds: Array.from(event.target.selectedOptions).map((option) => option.value) }))} className="h-36 w-full rounded-[4px] border border-line px-3 py-2 text-sm">
                        {products.map((item) => <option key={item.id} value={item.id}>{item.title} · {item.id}</option>)}
                      </select>
                    </label>
                    <label className="block">
                      <span className="mb-2 block text-sm font-bold text-ink">排除商品</span>
                      <select multiple value={form.excludeProductIds} onChange={(event) => setForm((current) => ({ ...current, excludeProductIds: Array.from(event.target.selectedOptions).map((option) => option.value) }))} className="h-36 w-full rounded-[4px] border border-line px-3 py-2 text-sm">
                        {products.map((item) => <option key={item.id} value={item.id}>{item.title} · {item.id}</option>)}
                      </select>
                    </label>
                  </div>
                </div>
              </div>

              <div>
                <div className="mb-3 text-sm font-extrabold text-ink">用户限制</div>
                <div className="grid gap-4 md:grid-cols-3">
                  {membershipOptions.map((item) => {
                    const active = form.membershipLevels.includes(item.value)
                    return (
                      <button key={item.value} type="button" onClick={() => setForm((current) => ({ ...current, membershipLevels: toggleValue(current.membershipLevels, item.value) }))} className={`h-9 rounded-[4px] border px-3 text-xs font-extrabold ${active ? 'border-brand bg-brand-light text-brand' : 'border-line text-muted hover:border-brand hover:text-brand'}`}>{item.label}</button>
                    )
                  })}
                  <label className="flex items-center gap-2 text-sm font-bold text-muted">
                    <input type="checkbox" checked={form.firstOrderOnly} onChange={(event) => setForm((current) => ({ ...current, firstOrderOnly: event.target.checked }))} className="accent-brand" />
                    仅首单
                  </label>
                  <label className="flex items-center gap-2 text-sm font-bold text-muted">
                    <input type="checkbox" checked={form.newUserOnly} onChange={(event) => setForm((current) => ({ ...current, newUserOnly: event.target.checked }))} className="accent-brand" />
                    仅注册 30 天内新用户
                  </label>
                </div>
                <div className="mt-4 grid gap-4 lg:grid-cols-2">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">指定通行证</span>
                    <textarea value={form.passportNos} onChange={(event) => setForm((current) => ({ ...current, passportNos: event.target.value }))} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" placeholder="每行一个通行证，可留空" />
                  </label>
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">指定用户 ID</span>
                    <textarea value={form.userIds} onChange={(event) => setForm((current) => ({ ...current, userIds: event.target.value }))} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" placeholder="每行一个用户 uuid，可留空" />
                  </label>
                </div>
              </div>

              <div>
                <div className="mb-3 text-sm font-extrabold text-ink">使用限制与叠加</div>
                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
                  <label className="block">
                    <span className="mb-2 block text-sm font-bold text-ink">总数量</span>
                    <input type="number" min="1" value={form.totalQuantity} onChange={(event) => setForm((current) => ({ ...current, totalQuantity: event.target.value }))} 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 type="number" min="0" value={form.perUser} onChange={(event) => setForm((current) => ({ ...current, perUser: event.target.value }))} 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 type="number" min="0" value={form.perDay} onChange={(event) => setForm((current) => ({ ...current, perDay: event.target.value }))} 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 type="number" min="0" step="0.01" value={form.budgetAmount} onChange={(event) => setForm((current) => ({ ...current, budgetAmount: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                  </label>
                  <label className="flex items-center gap-2 text-sm font-bold text-muted">
                    <input type="checkbox" checked={form.allowMemberDiscount} onChange={(event) => setForm((current) => ({ ...current, allowMemberDiscount: event.target.checked }))} className="accent-brand" />
                    和会员折扣叠加
                  </label>
                </div>
              </div>
            </section>

            <aside className="border-t border-line bg-bg/60 px-5 py-5 xl:border-l xl:border-t-0">
              <div className="text-sm font-extrabold text-ink">试算预览</div>
              <div className="mt-4 space-y-4">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">试算商品</span>
                  <select value={previewProductId} onChange={(event) => setPreviewProductId(event.target.value)} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                    {products.map((item) => <option key={item.id} value={item.id}>{item.title}</option>)}
                  </select>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">数量</span>
                  <input type="number" min="1" value={previewQuantity} onChange={(event) => setPreviewQuantity(event.target.value)} 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>
                  <select value={previewMembershipLevel} onChange={(event) => setPreviewMembershipLevel(event.target.value as 'registered' | 'junior' | 'senior')} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                    {membershipOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
                  </select>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">模拟通行证</span>
                  <input value={previewPassportNo} onChange={(event) => setPreviewPassportNo(event.target.value)} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                </label>
                <button type="button" onClick={() => void runPreview()} className="h-9 w-full rounded-[4px] border border-brand bg-white text-sm font-extrabold text-brand hover:bg-brand-light">试算优惠</button>
                {selectedPreviewProduct && <div className="text-xs font-bold text-muted">当前商品原价：¥{yuan(selectedPreviewProduct.priceAmount).toLocaleString()}</div>}
                {previewError && <div className="rounded-[4px] border border-red-100 bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{previewError}</div>}
                {preview && (
                  <div className="space-y-2 rounded-[4px] border border-line bg-white p-3 text-xs font-bold text-muted">
                    <div className="flex justify-between"><span>商品小计</span><span>¥{yuan(preview.subtotalAmount).toLocaleString()}</span></div>
                    <div className="flex justify-between"><span>会员折扣</span><span>- ¥{yuan(preview.memberDiscountAmount).toLocaleString()}</span></div>
                    <div className="flex justify-between"><span>优惠码</span><span>- ¥{yuan(preview.couponDiscountAmount).toLocaleString()}</span></div>
                    <div className="flex justify-between border-t border-line pt-2 text-ink"><span>应付</span><span>¥{yuan(preview.totalAmount).toLocaleString()}</span></div>
                    {preview.couponPreview && <div className="pt-2 text-brand">可用：{preview.couponPreview.name}，优惠基数 ¥{yuan(preview.couponPreview.discountBaseAmount || 0).toLocaleString()}</div>}
                  </div>
                )}
              </div>
            </aside>
          </div>
        )}
      </form>
    </AdminShell>
  )
}
