'use client'

import { useEffect, useMemo, useState } from 'react'
import { Bell, CheckCircle2, RefreshCw, RotateCcw, Save, Send, Settings2 } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import {
  backend,
  type BackendNotification,
  type BackendNotificationBatch,
  type BackendNotificationTargetType,
  type BackendNotificationTemplate,
} from '@/lib/backend'

type TabKey = 'records' | 'send' | 'templates'

const tabs: Array<{ key: TabKey; label: string }> = [
  { key: 'records', label: '发送记录' },
  { key: 'send', label: '人工发布' },
  { key: 'templates', label: '系统模板' },
]

const channelOptions = [
  { label: '站内信', value: 'in_app' },
  { label: '微信订阅', value: 'wechat_subscribe' },
  { label: '短信', value: 'sms' },
  { label: '邮件', value: 'email' },
]

const targetOptions: Array<{ label: string; value: BackendNotificationTargetType; hint: string }> = [
  { label: '全部用户', value: 'all', hint: '留空即可' },
  { label: '指定用户', value: 'user_ids', hint: '输入 UUID、手机号或通行证号，逗号或换行分隔' },
  { label: '会员等级', value: 'membership_level', hint: 'registered, junior, senior' },
  { label: '订单状态', value: 'order_status', hint: 'pending_payment, paid, closed 等订单状态' },
  { label: '服务状态', value: 'service_status', hint: 'pending, assigned, quoted, completed 等服务状态' },
  { label: '课程报名', value: 'course_registrations', hint: 'registered, checked_in, cancelled 或 JSON' },
  { label: '活动报名', value: 'event_registrations', hint: 'registered, checked_in, cancelled 或 JSON' },
  { label: '专家身份', value: 'experts', hint: '留空默认 published，可填 published/offline' },
]

const statusLabel: Record<string, string> = {
  queued: '待发送',
  sent: '已发送',
  failed: '失败',
  skipped: '已跳过',
  draft: '草稿',
  scheduled: '已计划',
  sending: '发送中',
  cancelled: '已取消',
  active: '启用',
  disabled: '停用',
}

const categoryLabel: Record<string, string> = {
  platform: '平台',
  account: '账号',
  order: '订单',
  membership: '会员',
  service: '服务',
  learning: '学习活动',
  expert: '专家',
  invoice: '发票',
  manual: '人工',
}

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

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

function parseTargetFilters(type: BackendNotificationTargetType, raw: string) {
  const value = raw.trim()
  if (!value || type === 'all') return {}
  if (value.startsWith('{')) {
    try {
      const parsed = JSON.parse(value)
      return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {}
    } catch {
      return {}
    }
  }
  const values = splitValues(value)
  if (type === 'user_ids') return { userKeys: values }
  if (type === 'membership_level') return { membershipLevels: values }
  if (type === 'order_status') return { statuses: values }
  if (type === 'service_status') return { statuses: values }
  if (type === 'course_registrations') return { statuses: values }
  if (type === 'event_registrations') return { statuses: values }
  if (type === 'experts') return { statuses: values }
  return {}
}

function statusClass(status: string) {
  if (status === 'sent' || status === 'active') return 'bg-emerald-50 text-emerald-700'
  if (status === 'failed' || status === 'skipped' || status === 'disabled') return 'bg-red-50 text-red-700'
  if (status === 'queued' || status === 'scheduled' || status === 'sending') return 'bg-amber-50 text-amber-700'
  return 'bg-bg text-muted'
}

function emptyBatchDraft() {
  return {
    title: '',
    body: '',
    actionUrl: '',
    targetType: 'all' as BackendNotificationTargetType,
    targetFilterText: '',
    channels: ['in_app'],
    priority: 'normal',
    sendNow: true,
  }
}

export default function AdminNotificationsPage() {
  const [activeTab, setActiveTab] = useState<TabKey>('records')
  const [records, setRecords] = useState<BackendNotification[]>([])
  const [recordStatus, setRecordStatus] = useState('')
  const [recordChannel, setRecordChannel] = useState('')
  const [batches, setBatches] = useState<BackendNotificationBatch[]>([])
  const [templates, setTemplates] = useState<BackendNotificationTemplate[]>([])
  const [selectedTemplateKey, setSelectedTemplateKey] = useState('')
  const [templateDraft, setTemplateDraft] = useState<BackendNotificationTemplate | null>(null)
  const [batchDraft, setBatchDraft] = useState(emptyBatchDraft)
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  const selectedTemplate = useMemo(
    () => templates.find((item) => item.templateKey === selectedTemplateKey) || templates[0] || null,
    [selectedTemplateKey, templates],
  )

  async function reloadRecords(nextStatus = recordStatus, nextChannel = recordChannel) {
    setLoading(true)
    try {
      const result = await backend.adminNotifications({ status: nextStatus, channel: nextChannel, pageSize: 100 })
      setRecords(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '通知记录加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function reloadBatches() {
    try {
      const result = await backend.adminNotificationBatches({ pageSize: 50 })
      setBatches(result.items)
    } catch (err) {
      setError(err instanceof Error ? err.message : '通知批次加载失败')
    }
  }

  async function reloadTemplates() {
    try {
      const result = await backend.adminNotificationTemplates()
      setTemplates(result.items)
      setSelectedTemplateKey((current) => current || result.items[0]?.templateKey || '')
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '通知模板加载失败')
    }
  }

  async function reloadAll() {
    await Promise.all([reloadRecords(), reloadBatches(), reloadTemplates()])
  }

  useEffect(() => {
    void reloadAll()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (selectedTemplate) setTemplateDraft({ ...selectedTemplate })
  }, [selectedTemplate])

  async function dispatchQueue() {
    setSaving(true)
    try {
      const result = await backend.dispatchNotifications()
      setMessage(`已发送 ${result.sentCount} 条，跳过 ${result.skippedCount} 条`)
      await reloadRecords()
    } catch (err) {
      setError(err instanceof Error ? err.message : '队列派发失败')
    } finally {
      setSaving(false)
    }
  }

  async function retryRecord(item: BackendNotification) {
    try {
      await backend.retryNotification(item.id)
      setMessage('通知已重试')
      await reloadRecords()
    } catch (err) {
      setError(err instanceof Error ? err.message : '通知重试失败')
    }
  }

  function setBatchChannel(channel: string, checked: boolean) {
    setBatchDraft((current) => {
      const channels = checked
        ? Array.from(new Set([...current.channels, channel]))
        : current.channels.filter((item) => item !== channel)
      return { ...current, channels: channels.length ? channels : ['in_app'] }
    })
  }

  async function createBatch() {
    setSaving(true)
    setMessage('')
    setError('')
    try {
      const result = await backend.createNotificationBatch({
        title: batchDraft.title,
        body: batchDraft.body,
        actionUrl: batchDraft.actionUrl,
        targetType: batchDraft.targetType,
        targetFilters: parseTargetFilters(batchDraft.targetType, batchDraft.targetFilterText),
        channels: batchDraft.channels,
        priority: batchDraft.priority,
        sendNow: batchDraft.sendNow,
      })
      setMessage(batchDraft.sendNow ? `已发送 ${result.sentCount} 条，跳过 ${result.skippedCount} 条` : `批次 ${result.batchNo} 已创建`)
      setBatchDraft(emptyBatchDraft())
      await Promise.all([reloadBatches(), reloadRecords()])
    } catch (err) {
      setError(err instanceof Error ? err.message : '人工消息发布失败')
    } finally {
      setSaving(false)
    }
  }

  async function sendBatch(item: BackendNotificationBatch) {
    try {
      const result = await backend.sendNotificationBatch(item.id)
      setMessage(`批次 ${result.batchNo} 已发送 ${result.sentCount} 条，跳过 ${result.skippedCount} 条`)
      await Promise.all([reloadBatches(), reloadRecords()])
    } catch (err) {
      setError(err instanceof Error ? err.message : '批次发送失败')
    }
  }

  function setTemplateChannel(channel: string, checked: boolean) {
    setTemplateDraft((current) => {
      if (!current) return current
      const next = checked
        ? Array.from(new Set([...current.defaultChannels, channel]))
        : current.defaultChannels.filter((item) => item !== channel)
      return { ...current, defaultChannels: next.length ? next : ['in_app'] }
    })
  }

  async function saveTemplate() {
    if (!templateDraft) return
    setSaving(true)
    try {
      const updated = await backend.updateNotificationTemplate(templateDraft.templateKey, {
        titleTemplate: templateDraft.titleTemplate,
        bodyTemplate: templateDraft.bodyTemplate,
        actionUrlTemplate: templateDraft.actionUrlTemplate,
        defaultChannels: templateDraft.defaultChannels,
        priority: templateDraft.priority,
        status: templateDraft.status,
        variablesSchema: templateDraft.variablesSchema,
      })
      setMessage(`模板 ${updated.templateKey} 已保存`)
      await reloadTemplates()
    } catch (err) {
      setError(err instanceof Error ? err.message : '模板保存失败')
    } finally {
      setSaving(false)
    }
  }

  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="mb-3 flex flex-wrap items-center justify-between gap-2 border border-line bg-white px-3 py-2">
        <div className="flex flex-wrap gap-2">
          {tabs.map((item) => (
            <button
              key={item.key}
              type="button"
              onClick={() => setActiveTab(item.key)}
              className={`h-9 rounded-[4px] px-3 text-xs font-extrabold ${activeTab === item.key ? 'bg-ink text-white' : 'border border-line text-muted hover:border-brand hover:text-brand'}`}
            >
              {item.label}
            </button>
          ))}
        </div>
        <button type="button" onClick={() => void reloadAll()} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
          <RefreshCw className="h-3.5 w-3.5" />
          刷新
        </button>
      </div>

      {activeTab === 'records' && (
        <section className="border border-line bg-white">
          <div className="flex flex-col gap-2 border-b border-line px-3 py-2 lg:flex-row lg:items-center">
            <select value={recordStatus} onChange={(event) => { setRecordStatus(event.target.value); void reloadRecords(event.target.value, recordChannel) }} className="h-9 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
              <option value="">全部状态</option>
              <option value="queued">待发送</option>
              <option value="sent">已发送</option>
              <option value="failed">失败</option>
              <option value="skipped">已跳过</option>
            </select>
            <select value={recordChannel} onChange={(event) => { setRecordChannel(event.target.value); void reloadRecords(recordStatus, event.target.value) }} className="h-9 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
              <option value="">全部渠道</option>
              {channelOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
            </select>
            <button type="button" disabled={saving} onClick={() => void dispatchQueue()} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white disabled:opacity-60">
              <Send className="h-3.5 w-3.5" />
              派发队列
            </button>
          </div>

          <div className="hidden grid-cols-[88px_88px_1fr_180px_120px_130px] border-b border-line px-3 py-2 text-[11px] font-extrabold text-soft xl:grid">
            <span>状态</span><span>渠道</span><span>消息</span><span>用户</span><span>分类</span><span>时间</span>
          </div>
          {loading && <div className="px-4 py-8 text-sm font-bold text-muted">正在加载通知记录...</div>}
          {!loading && records.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无通知记录</div>}
          {!loading && records.map((item) => (
            <div key={item.id} className="grid gap-2 border-b border-line px-3 py-3 text-xs hover:bg-bg xl:grid-cols-[88px_88px_1fr_180px_120px_130px] xl:items-center">
              <span className={`inline-flex h-6 w-fit items-center px-2 font-extrabold ${statusClass(item.status)}`}>{statusLabel[item.status] || item.status}</span>
              <span className="font-bold text-muted">{channelOptions.find((option) => option.value === item.channel)?.label || item.channel}</span>
              <span className="min-w-0">
                <span className="block truncate text-sm font-extrabold text-ink">{item.title || item.templateKey}</span>
                <span className="mt-1 block truncate text-[11px] text-muted">{item.body || item.failedReason || '-'}</span>
                {item.failedReason && <span className="mt-1 block truncate text-[11px] font-bold text-red-600">{item.failedReason}</span>}
              </span>
              <span className="truncate font-bold text-muted">{item.userName || item.userPhone || item.passportNo || item.userId || '-'}</span>
              <span className="font-bold text-muted">{categoryLabel[item.category || ''] || item.category || item.scene}</span>
              <span className="flex items-center justify-between gap-2 font-bold text-muted">
                {formatDate(item.createdAt)}
                {['failed', 'skipped', 'queued'].includes(item.status) && (
                  <button type="button" onClick={() => void retryRecord(item)} className="inline-flex h-7 items-center gap-1 rounded-[4px] border border-line px-2 text-[11px] font-extrabold text-muted hover:border-brand hover:text-brand">
                    <RotateCcw className="h-3 w-3" />
                    重试
                  </button>
                )}
              </span>
            </div>
          ))}
        </section>
      )}

      {activeTab === 'send' && (
        <div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_420px]">
          <section className="border border-line bg-white p-4">
            <div className="mb-4 flex items-center gap-2 text-base font-extrabold text-ink">
              <Bell className="h-4 w-4 text-brand" />
              人工发布
            </div>
            <div className="grid gap-3">
              <label>
                <span className="mb-1.5 block text-xs font-extrabold text-muted">标题</span>
                <input value={batchDraft.title} onChange={(event) => setBatchDraft({ ...batchDraft, title: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
              </label>
              <label>
                <span className="mb-1.5 block text-xs font-extrabold text-muted">正文</span>
                <textarea value={batchDraft.body} onChange={(event) => setBatchDraft({ ...batchDraft, body: event.target.value })} rows={5} className="w-full resize-none rounded-[4px] border border-line px-3 py-2 text-sm font-bold outline-none focus:border-brand" />
              </label>
              <label>
                <span className="mb-1.5 block text-xs font-extrabold text-muted">跳转链接</span>
                <input value={batchDraft.actionUrl} onChange={(event) => setBatchDraft({ ...batchDraft, actionUrl: event.target.value })} placeholder="/account/membership" className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
              </label>
              <div className="grid gap-3 md:grid-cols-2">
                <label>
                  <span className="mb-1.5 block text-xs font-extrabold text-muted">目标范围</span>
                  <select value={batchDraft.targetType} onChange={(event) => setBatchDraft({ ...batchDraft, targetType: event.target.value as BackendNotificationTargetType, targetFilterText: '' })} className="h-10 w-full rounded-[4px] border border-line px-2 text-sm font-bold outline-none focus:border-brand">
                    {targetOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
                  </select>
                </label>
                <label>
                  <span className="mb-1.5 block text-xs font-extrabold text-muted">优先级</span>
                  <select value={batchDraft.priority} onChange={(event) => setBatchDraft({ ...batchDraft, priority: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-2 text-sm font-bold outline-none focus:border-brand">
                    <option value="normal">普通</option>
                    <option value="high">重要</option>
                    <option value="urgent">紧急</option>
                    <option value="low">低</option>
                  </select>
                </label>
              </div>
              <label>
                <span className="mb-1.5 block text-xs font-extrabold text-muted">目标条件</span>
                <textarea
                  value={batchDraft.targetFilterText}
                  onChange={(event) => setBatchDraft({ ...batchDraft, targetFilterText: event.target.value })}
                  rows={4}
                  placeholder={targetOptions.find((item) => item.value === batchDraft.targetType)?.hint}
                  className="w-full resize-none rounded-[4px] border border-line px-3 py-2 text-sm font-bold outline-none focus:border-brand"
                />
              </label>
              <div>
                <div className="mb-2 text-xs font-extrabold text-muted">渠道</div>
                <div className="flex flex-wrap gap-3">
                  {channelOptions.map((item) => (
                    <label key={item.value} className="inline-flex items-center gap-2 text-sm font-bold text-ink">
                      <input type="checkbox" checked={batchDraft.channels.includes(item.value)} onChange={(event) => setBatchChannel(item.value, event.target.checked)} className="h-4 w-4 accent-brand" />
                      {item.label}
                    </label>
                  ))}
                </div>
              </div>
              <label className="inline-flex items-center gap-2 text-sm font-bold text-ink">
                <input type="checkbox" checked={batchDraft.sendNow} onChange={(event) => setBatchDraft({ ...batchDraft, sendNow: event.target.checked })} className="h-4 w-4 accent-brand" />
                创建后立即发送
              </label>
              <button type="button" disabled={saving} onClick={() => void createBatch()} className="inline-flex h-10 w-fit items-center gap-1.5 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
                <Send className="h-4 w-4" />
                发布消息
              </button>
            </div>
          </section>

          <section className="border border-line bg-white">
            <div className="border-b border-line px-4 py-3 text-sm font-extrabold text-ink">最近批次</div>
            {batches.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无批次</div>}
            {batches.map((item) => (
              <div key={item.id} className="border-b border-line px-4 py-3 text-xs last:border-b-0">
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="truncate text-sm font-extrabold text-ink">{item.title}</div>
                    <div className="mt-1 font-bold text-muted">{item.batchNo} · {statusLabel[item.status] || item.status}</div>
                  </div>
                  {!['sent', 'sending', 'cancelled'].includes(item.status) && (
                    <button type="button" onClick={() => void sendBatch(item)} className="inline-flex h-7 shrink-0 items-center gap-1 rounded-[4px] bg-ink px-2 text-[11px] font-extrabold text-white">
                      <Send className="h-3 w-3" />
                      发送
                    </button>
                  )}
                </div>
                <div className="mt-2 grid grid-cols-3 gap-2 font-bold text-muted">
                  <span>目标 {item.recipientCount}</span>
                  <span>成功 {item.sentCount}</span>
                  <span>跳过 {item.skippedCount}</span>
                </div>
                <div className="mt-2 line-clamp-2 text-muted">{item.body}</div>
              </div>
            ))}
          </section>
        </div>
      )}

      {activeTab === 'templates' && (
        <div className="grid gap-3 xl:grid-cols-[360px_minmax(0,1fr)]">
          <section className="max-h-[calc(100vh-180px)] overflow-auto border border-line bg-white">
            {templates.map((item) => (
              <button
                type="button"
                key={item.templateKey}
                onClick={() => setSelectedTemplateKey(item.templateKey)}
                className={`block w-full border-b border-line px-3 py-3 text-left text-xs hover:bg-bg ${selectedTemplate?.templateKey === item.templateKey ? 'bg-brand-light' : 'bg-white'}`}
              >
                <div className="flex items-center justify-between gap-2">
                  <span className="truncate text-sm font-extrabold text-ink">{item.titleTemplate}</span>
                  <span className={`shrink-0 px-2 py-1 text-[10px] font-extrabold ${statusClass(item.status)}`}>{statusLabel[item.status] || item.status}</span>
                </div>
                <div className="mt-1 truncate font-bold text-muted">{item.templateKey}</div>
                <div className="mt-1 font-bold text-soft">{categoryLabel[item.category] || item.category} · {item.scene}</div>
              </button>
            ))}
          </section>

          <section className="border border-line bg-white p-4">
            {!templateDraft && <div className="text-sm font-bold text-muted">请选择模板</div>}
            {templateDraft && (
              <div className="grid gap-3">
                <div className="flex items-center gap-2 text-base font-extrabold text-ink">
                  <Settings2 className="h-4 w-4 text-brand" />
                  {templateDraft.templateKey}
                </div>
                <label>
                  <span className="mb-1.5 block text-xs font-extrabold text-muted">标题模板</span>
                  <input value={templateDraft.titleTemplate} onChange={(event) => setTemplateDraft({ ...templateDraft, titleTemplate: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
                </label>
                <label>
                  <span className="mb-1.5 block text-xs font-extrabold text-muted">正文模板</span>
                  <textarea value={templateDraft.bodyTemplate} onChange={(event) => setTemplateDraft({ ...templateDraft, bodyTemplate: event.target.value })} rows={5} className="w-full resize-none rounded-[4px] border border-line px-3 py-2 text-sm font-bold outline-none focus:border-brand" />
                </label>
                <label>
                  <span className="mb-1.5 block text-xs font-extrabold text-muted">跳转模板</span>
                  <input value={templateDraft.actionUrlTemplate} onChange={(event) => setTemplateDraft({ ...templateDraft, actionUrlTemplate: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand" />
                </label>
                <div className="grid gap-3 md:grid-cols-2">
                  <label>
                    <span className="mb-1.5 block text-xs font-extrabold text-muted">状态</span>
                    <select value={templateDraft.status} onChange={(event) => setTemplateDraft({ ...templateDraft, status: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-2 text-sm font-bold outline-none focus:border-brand">
                      <option value="active">启用</option>
                      <option value="disabled">停用</option>
                    </select>
                  </label>
                  <label>
                    <span className="mb-1.5 block text-xs font-extrabold text-muted">优先级</span>
                    <select value={templateDraft.priority} onChange={(event) => setTemplateDraft({ ...templateDraft, priority: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-2 text-sm font-bold outline-none focus:border-brand">
                      <option value="normal">普通</option>
                      <option value="high">重要</option>
                      <option value="urgent">紧急</option>
                      <option value="low">低</option>
                    </select>
                  </label>
                </div>
                <div>
                  <div className="mb-2 text-xs font-extrabold text-muted">默认渠道</div>
                  <div className="flex flex-wrap gap-3">
                    {channelOptions.map((item) => (
                      <label key={item.value} className="inline-flex items-center gap-2 text-sm font-bold text-ink">
                        <input type="checkbox" checked={templateDraft.defaultChannels.includes(item.value)} onChange={(event) => setTemplateChannel(item.value, event.target.checked)} className="h-4 w-4 accent-brand" />
                        {item.label}
                      </label>
                    ))}
                  </div>
                </div>
                <button type="button" disabled={saving} onClick={() => void saveTemplate()} className="inline-flex h-10 w-fit items-center gap-1.5 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
                  <Save className="h-4 w-4" />
                  保存模板
                </button>
                <div className="rounded-[4px] bg-bg px-3 py-2 text-xs font-bold text-muted">
                  变量缺失时会保留形如 {'{{变量名}}'} 的占位。
                </div>
                {templateDraft.status === 'active' && <div className="inline-flex w-fit items-center gap-1.5 rounded-[4px] bg-emerald-50 px-2 py-1 text-xs font-extrabold text-emerald-700"><CheckCircle2 className="h-3.5 w-3.5" />模板启用中</div>}
              </div>
            )}
          </section>
        </div>
      )}
    </AdminShell>
  )
}
