'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendEventProduct } from '@/lib/backend'
import type { CourseAccessState } from '@/types'

type EventFormState = Omit<BackendEventProduct, 'type' | 'purchaseFlow' | 'fulfillmentFlow' | 'priceAmount'>

const accessRows: { label: string; accessKey: 'registeredAccess' | 'juniorAccess' | 'seniorAccess'; priceKey: 'registeredPriceAmount' | 'juniorPriceAmount' | 'seniorPriceAmount' }[] = [
  { label: '注册用户', accessKey: 'registeredAccess', priceKey: 'registeredPriceAmount' },
  { label: '初级会员', accessKey: 'juniorAccess', priceKey: 'juniorPriceAmount' },
  { label: '高级会员', accessKey: 'seniorAccess', priceKey: 'seniorPriceAmount' },
]

const blankForm: EventFormState = {
  id: '',
  productId: '',
  slug: '',
  title: '',
  summary: '',
  productStatus: 'draft',
  status: 'draft',
  eventType: 'public',
  topic: '峰会论坛',
  eventFormat: '线下活动',
  coverUrl: '',
  coverLabel: '',
  audience: '',
  highlights: ['主题分享', '案例交流', '互动答疑', '资源对接'],
  agenda: ['签到入场', '主题分享', '交流讨论', '活动结束'],
  startsAt: '',
  endsAt: '',
  location: '大连市大数据研究院',
  isOnline: false,
  onlineUrl: '',
  capacity: 100,
  registeredCount: 0,
  initialRegisteredCount: 0,
  registeredAccess: 'paid',
  juniorAccess: 'paid',
  seniorAccess: 'paid',
  registeredPriceAmount: 20000,
  juniorPriceAmount: 18000,
  seniorPriceAmount: 16000,
  memberLevelRequired: 0,
  recommended: false,
  sortOrder: 10,
}

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

function toSafeNumber(value: string | number | null | undefined) {
  const parsed = Number(value)
  if (!Number.isFinite(parsed)) return 0
  return Math.max(0, parsed)
}

function displayYuan(value: unknown) {
  const amount = Number(value)
  if (!Number.isFinite(amount)) return ''
  return String(Math.round(amount / 100))
}

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

function lines(value: string[]) {
  return value.join('\n')
}

function arrayFromLines(value: string) {
  return value.split(/\n|；|;/).map((item) => item.trim()).filter(Boolean)
}

function isSupportedCoverImage(file: File) {
  return ['image/jpeg', 'image/png', 'image/webp'].includes(file.type)
}

function productStatusForEventStatus(status?: EventFormState['status']): EventFormState['productStatus'] {
  if (status === 'registration_closed') return 'published'
  if (status === 'offline' || status === 'deleted') return 'offline'
  if (status === 'published') return 'published'
  return 'draft'
}

export function EventProductForm({ productId }: { productId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState<EventFormState>(blankForm)
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')
  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    if (!productId) return
    void backend.adminEvents().then((result) => {
      const item = result.items.find((entry) => entry.id === productId)
      if (!item) {
        setError('活动不存在')
        return
      }
      setForm({
        ...item,
        productStatus: item.productStatus || productStatusForEventStatus(item.status),
        status: item.status === 'deleted' ? 'offline' : item.status,
        startsAt: toInputDateTime(item.startsAt),
        endsAt: toInputDateTime(item.endsAt),
        highlights: item.highlights || [],
        agenda: item.agenda || [],
      })
    }).catch((err) => setError(err instanceof Error ? err.message : '活动加载失败'))
  }, [productId])

  function buildPayload() {
    const slug = form.slug || slugify(form.title)
    return {
      ...form,
      productId: productId || form.productId || `event-${slug}`,
      slug,
      status: form.status,
      productStatus: productStatusForEventStatus(form.status),
      coverLabel: '',
      highlights: form.highlights,
      agenda: form.agenda,
      registeredPriceAmount: form.registeredAccess === 'paid' ? form.registeredPriceAmount : 0,
      juniorPriceAmount: form.juniorAccess === 'paid' ? form.juniorPriceAmount : 0,
      seniorPriceAmount: form.seniorAccess === 'paid' ? form.seniorPriceAmount : 0,
    }
  }

  return (
    <AdminShell title={productId ? '编辑活动' : '新增活动'} description="维护用户端活动展示、报名规则、价格权益、时间地点和现场核销凭证。">
      <form
        className="max-w-[980px] border border-line bg-white"
        onSubmit={async (event) => {
          event.preventDefault()
          try {
            await backend.saveAdminEvent(productId || null, buildPayload())
            setSaved('活动已保存')
            router.push('/admin/events')
          } catch (err) {
            setError(err instanceof Error ? err.message : '活动保存失败')
          }
        }}
      >
        <div className="border-b border-line px-5 py-4">
          <div className="text-base font-extrabold text-ink">基础展示</div>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="text-xs font-bold text-muted">活动标题</span>
              <input value={form.title} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} required className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">slug</span>
              <input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="不填按标题生成" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
          </div>
          <label className="mt-4 block">
            <span className="text-xs font-bold text-muted">活动摘要</span>
            <textarea value={form.summary} onChange={(event) => setForm((current) => ({ ...current, summary: event.target.value }))} required rows={3} className="mt-1 w-full rounded-[4px] border border-line p-3 text-sm" />
          </label>
          <div className="mt-4 grid gap-4 md:grid-cols-3">
            <label className="block">
              <span className="text-xs font-bold text-muted">活动主题</span>
              <select value={form.topic} onChange={(event) => setForm((current) => ({ ...current, topic: event.target.value as EventFormState['topic'] }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                {['峰会论坛', '政策研讨', 'AI应用', '数据安全', '企业参访'].map((item) => <option key={item}>{item}</option>)}
              </select>
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">活动形式</span>
              <select value={form.eventFormat} onChange={(event) => setForm((current) => ({ ...current, eventFormat: event.target.value as EventFormState['eventFormat'], isOnline: event.target.value === '线上活动' }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                {['线下活动', '线上活动', '工作坊', '参访交流'].map((item) => <option key={item}>{item}</option>)}
              </select>
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">展示类型</span>
              <select value={form.eventType} onChange={(event) => setForm((current) => ({ ...current, eventType: event.target.value as EventFormState['eventType'] }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                <option value="public">公开活动</option>
                <option value="free">免费活动</option>
                <option value="pro">会员活动</option>
                <option value="max">高级会员活动</option>
              </select>
            </label>
          </div>
          <div className="mt-4 grid gap-4 md:grid-cols-[1fr_180px] md:items-end">
            <div className="min-h-10 rounded-[4px] border border-line bg-bg px-3 py-2 text-xs font-bold leading-5 text-muted">
              {form.coverUrl ? '已上传活动封面，用户端将显示真实图片。' : '尚未上传封面；用户端显示朴素空态。'}
            </div>
            <label className="inline-flex h-10 cursor-pointer items-center justify-center gap-2 rounded-[4px] border border-line text-sm font-extrabold text-ink hover:border-brand hover:text-brand">
              <Upload className="h-4 w-4" />
              {uploading ? '上传中...' : '上传封面'}
              <input
                type="file"
                accept="image/jpeg,image/png,image/webp"
                className="sr-only"
                onChange={async (event) => {
                  const file = event.target.files?.[0]
                  if (!file) return
                  if (!isSupportedCoverImage(file)) {
                    setError('封面只支持 JPG、PNG 或 WebP。请不要上传 HEIC/HEIF，用户端可能无法显示。')
                    event.target.value = ''
                    return
                  }
                  setUploading(true)
                  try {
                    const uploaded = await backend.uploadAdminFile(file)
                    setForm((current) => ({ ...current, coverUrl: uploaded.url }))
                  } catch (err) {
                    setError(err instanceof Error ? err.message : '封面上传失败')
                  } finally {
                    setUploading(false)
                    event.target.value = ''
                  }
                }}
              />
            </label>
          </div>
        </div>

        <div className="border-b border-line px-5 py-4">
          <div className="text-base font-extrabold text-ink">时间地点与名额</div>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="text-xs font-bold text-muted">开始时间</span>
              <input value={form.startsAt || ''} onChange={(event) => setForm((current) => ({ ...current, startsAt: event.target.value }))} type="datetime-local" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">结束时间</span>
              <input value={form.endsAt || ''} onChange={(event) => setForm((current) => ({ ...current, endsAt: event.target.value }))} type="datetime-local" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
          </div>
          <div className="mt-4 grid gap-4 md:grid-cols-[130px_1fr_1fr]">
            <label className="block">
              <span className="text-xs font-bold text-muted">线上活动</span>
              <select value={form.isOnline ? 'yes' : 'no'} onChange={(event) => setForm((current) => ({ ...current, isOnline: event.target.value === 'yes' }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                <option value="no">否</option>
                <option value="yes">是</option>
              </select>
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">{form.isOnline ? '线上展示地点' : '线下地点'}</span>
              <input value={form.location} onChange={(event) => setForm((current) => ({ ...current, location: event.target.value }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            {form.isOnline && (
              <label className="block">
                <span className="text-xs font-bold text-muted">线上会议/直播链接</span>
                <input value={form.onlineUrl} onChange={(event) => setForm((current) => ({ ...current, onlineUrl: event.target.value }))} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              </label>
            )}
          </div>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="text-xs font-bold text-muted">活动容量</span>
              <input value={form.capacity} onChange={(event) => setForm((current) => ({ ...current, capacity: Number(event.target.value || 0) }))} type="number" min="0" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">初始报名人数</span>
              <input value={form.initialRegisteredCount} onChange={(event) => setForm((current) => ({ ...current, initialRegisteredCount: Number(event.target.value || 0) }))} type="number" min="0" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
          </div>
        </div>

        <div className="border-b border-line px-5 py-4">
          <div className="text-base font-extrabold text-ink">报名权限与分层价格（元）</div>
          <div className="mt-4 border border-line">
            {accessRows.map((row) => {
              const accessValue = form[row.accessKey] as CourseAccessState
              const priceValue = form[row.priceKey]
              return (
                <div key={row.accessKey} className="grid gap-3 border-b border-line p-3 last:border-b-0 md:grid-cols-[120px_160px_1fr] md:items-center">
                  <div className="text-sm font-extrabold text-ink">{row.label}</div>
                  <select value={accessValue} onChange={(event) => setForm((current) => ({ ...current, [row.accessKey]: event.target.value as CourseAccessState }))} className="h-10 rounded-[4px] border border-line px-3 text-sm">
                    <option value="closed">不可报名</option>
                    <option value="free">免费</option>
                    <option value="paid">收费</option>
                  </select>
                  <input
                    value={accessValue === 'paid' ? displayYuan(priceValue) : ''}
                    onChange={(event) => setForm((current) => ({ ...current, [row.priceKey]: toSafeNumber(event.target.value) * 100 }))}
                    disabled={accessValue !== 'paid'}
                    type="number"
                    min="0"
                    placeholder={accessValue === 'closed' ? '当前等级不可报名' : '免费'}
                    className="h-10 rounded-[4px] border border-line px-3 text-sm disabled:bg-bg disabled:text-soft"
                  />
                </div>
              )
            })}
          </div>
        </div>

        <div className="border-b border-line px-5 py-4">
          <div className="text-base font-extrabold text-ink">详情内容</div>
          <label className="mt-4 block">
            <span className="text-xs font-bold text-muted">适合人群</span>
            <textarea value={form.audience} onChange={(event) => setForm((current) => ({ ...current, audience: event.target.value }))} rows={3} className="mt-1 w-full rounded-[4px] border border-line p-3 text-sm" />
          </label>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="text-xs font-bold text-muted">活动亮点（一行一条）</span>
              <textarea value={lines(form.highlights)} onChange={(event) => setForm((current) => ({ ...current, highlights: arrayFromLines(event.target.value) }))} rows={6} className="mt-1 w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">活动安排（一行一条）</span>
              <textarea value={lines(form.agenda)} onChange={(event) => setForm((current) => ({ ...current, agenda: arrayFromLines(event.target.value) }))} rows={6} className="mt-1 w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>
          </div>
        </div>

        <div className="px-5 py-4">
          <div className="text-base font-extrabold text-ink">发布控制</div>
          <div className="mt-4 grid gap-4 md:grid-cols-3">
            <label className="block">
              <span className="text-xs font-bold text-muted">排序值</span>
              <input value={form.sortOrder} onChange={(event) => setForm((current) => ({ ...current, sortOrder: Number(event.target.value || 0) }))} type="number" className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              <span className="mt-1 block text-[11px] font-bold text-soft">同序号时，本活动优先，原有活动顺延。</span>
            </label>
            <label className="block">
              <span className="text-xs font-bold text-muted">状态</span>
              <select value={form.status} onChange={(event) => {
                const nextStatus = event.target.value as EventFormState['status']
                setForm((current) => ({ ...current, status: nextStatus, productStatus: productStatusForEventStatus(nextStatus) }))
              }} className="mt-1 h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                <option value="draft">草稿</option>
                <option value="published">已发布</option>
                <option value="registration_closed">报名关闭</option>
                <option value="offline">已下架</option>
              </select>
            </label>
            <label className="mt-6 flex h-10 items-center gap-2 text-sm font-extrabold text-ink">
              <input type="checkbox" checked={form.recommended} onChange={(event) => setForm((current) => ({ ...current, recommended: event.target.checked }))} />
              推荐到活动轮播
            </label>
          </div>

          {error && <div className="mt-4 text-sm font-bold text-red-700">{error}</div>}
          {saved && <div className="mt-4 text-sm font-bold text-green">{saved}</div>}
          <div className="mt-5 flex justify-end gap-3">
            <Link href="/admin/events" className="inline-flex h-10 items-center rounded-[4px] border border-line px-4 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">返回活动管理</Link>
            <button type="submit" className="h-10 rounded-[4px] bg-ink px-5 text-sm font-extrabold text-white hover:bg-brand">保存活动</button>
          </div>
        </div>
      </form>
    </AdminShell>
  )
}
