'use client'

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

const typeLabel: Record<string, string> = {
  course: '课程产品',
  event: '活动',
  data: '数据服务案例',
  agent: '智能体产品',
  membership: '会员方案',
}

function slugify(value: string) {
  return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
}

function NewCatalogProductInner() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const type = (searchParams.get('type') || 'course') as BackendProduct['type']
  const [error, setError] = useState('')
  const [form, setForm] = useState({ title: '', slug: '', summary: '', price: '99' })

  useEffect(() => {
    if (type === 'event') router.replace('/admin/events/new')
    if (type === 'data') router.replace('/admin/data-service/cases/new')
  }, [router, type])

  if (type === 'event' || type === 'data') {
    return (
      <AdminShell title="正在跳转" description="活动和数据服务案例已迁移到专用后台模块。">
        <div className="border border-line bg-white p-5 text-sm font-bold text-muted">正在进入专用维护页面...</div>
      </AdminShell>
    )
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const slug = form.slug || slugify(form.title)
    try {
      await backend.createAdminProduct({
        id: slug,
        slug,
        type,
        title: form.title,
        summary: form.summary,
        priceAmount: Math.round(Number(form.price || 0) * 100),
        status: 'draft',
      })
      const panel = type === 'course' ? 'courses' : type === 'agent' ? 'agents' : 'membership'
      router.push(`/admin/content?panel=${panel}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败')
    }
  }

  return (
    <AdminShell title={`新增${typeLabel[type] || '商品'}`} description="这里是独立新增页；后续课程、活动、数据会继续按前台字段拆成完整维护表单。">
      <form onSubmit={submit} className="max-w-[760px] space-y-4 border border-line bg-white p-5">
        {error && <div className="text-sm font-bold text-red-700">{error}</div>}
        <input value={form.title} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} required placeholder="标题" className="h-10 w-full border border-line px-3 text-sm" />
        <input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug，不填则根据标题生成" className="h-10 w-full border border-line px-3 text-sm" />
        <input value={form.price} onChange={(event) => setForm((current) => ({ ...current, price: event.target.value }))} type="number" min="0" placeholder="价格（元）" className="h-10 w-full border border-line px-3 text-sm" />
        <textarea value={form.summary} onChange={(event) => setForm((current) => ({ ...current, summary: event.target.value }))} rows={5} placeholder="摘要" className="w-full border border-line p-3 text-sm" />
        <button className="h-10 bg-brand px-5 text-sm font-extrabold text-white">保存草稿</button>
      </form>
    </AdminShell>
  )
}

export default function NewCatalogProductPage() {
  return (
    <Suspense fallback={<section className="grid min-h-screen place-items-center bg-[#f5f7fb] text-sm font-extrabold text-muted">正在加载新增商品...</section>}>
      <NewCatalogProductInner />
    </Suspense>
  )
}
