'use client'

import Link from 'next/link'
import { Suspense, useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { useSearchParams } from 'next/navigation'
import { Plus, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendExpert, type BackendNewsArticle, type BackendProduct, yuan } from '@/lib/backend'

const typeOptions = [
  { label: '会员', value: 'membership' },
  { label: '课程', value: 'course' },
  { label: '智能体', value: 'agent' },
] as const

const statusLabel: Record<string, string> = {
  draft: '草稿',
  published: '已发布',
  offline: '已下架',
  active: '启用',
  paused: '暂停',
  expired: '过期',
}

const availabilityLabel: Record<string, string> = {
  'this-week': '本周可约',
  'next-week': '下周可约',
  unavailable: '暂不可约',
}

const productTypeByPanel: Partial<Record<string, BackendProduct['type']>> = {
  membership: 'membership',
  courses: 'course',
  agents: 'agent',
}

const moduleMeta: Record<string, { title: string; description: string }> = {
  products: {
    title: '全部商品',
    description: '统一维护用户端与小程序端可购买的所有商品，支持按类型筛选、发布和下架。',
  },
  membership: {
    title: '会员商品',
    description: '维护初级会员、高级会员等会员类商品，数据会进入用户购买和会员权益链路。',
  },
  courses: {
    title: '课程商品',
    description: '维护课程类服务商品，控制用户端课程入口展示、价格和上下架状态。',
  },
  events: {
    title: '活动管理已迁移',
    description: '活动已从商品库迁移到活动运营模块，报名名单和核销入口在活动中心统一处理。',
  },
  data: {
    title: '数据服务案例已迁移',
    description: '数据案例已从商品库迁移到数据服务配置，交易统一进入服务需求申请。',
  },
  agents: {
    title: '智能体商品',
    description: '维护智能体服务商品，控制用户端智能体购买入口和订单履约入口。',
  },
  coupons: {
    title: '优惠码',
    description: '优惠码已迁移到独立后台模块，新增和编辑都在专门页面完成。',
  },
  news: {
    title: '资讯发布',
    description: '维护 web 新闻资讯、小程序资讯列表和首页动态内容。',
  },
  experts: {
    title: '专家资源库',
    description: '维护专家资料、擅长领域、预约价格和用户端专家平台展示状态。',
  },
}

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

function AdminContentInner() {
  const searchParams = useSearchParams()
  const panel = searchParams.get('panel') || 'products'
  const currentMeta = moduleMeta[panel] || moduleMeta.products
  const fixedProductType = productTypeByPanel[panel]
  const migratedPanelHref = panel === 'events' ? '/admin/events' : panel === 'data' ? '/admin/data-service/cases' : ''
  const isProductPanel = panel === 'products' || Boolean(fixedProductType)
  const [products, setProducts] = useState<BackendProduct[]>([])
  const [news, setNews] = useState<BackendNewsArticle[]>([])
  const [experts, setExperts] = useState<BackendExpert[]>([])
  const [type, setType] = useState('全部')
  const [saved, setSaved] = useState('')
  const [error, setError] = useState('')
  const [expertDraft, setExpertDraft] = useState({
    name: '',
    slug: '',
    title: '',
    organization: '',
    specialties: '',
    price: '1200',
    bio: '',
  })

  const visibleProducts = useMemo(() => {
    const productItems = products.filter((item) => item.type !== 'expert')
    if (fixedProductType) return productItems.filter((item) => item.type === fixedProductType)
    if (type === '全部') return productItems
    return productItems.filter((item) => item.type === type)
  }, [fixedProductType, products, type])

  async function reload() {
    try {
      const [productResult, newsResult, expertResult] = await Promise.all([
        backend.adminProducts(),
        backend.adminNews(),
        backend.adminExperts(),
      ])
      setProducts(productResult.items)
      setNews(newsResult.items)
      setExperts(expertResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '内容数据加载失败')
    }
  }

  useEffect(() => {
    queueMicrotask(() => void reload())
  }, [])

  async function setFeaturedNews(item: BackendNewsArticle, checked: boolean) {
    try {
      if (!checked) {
        await backend.updateAdminNews(item.id, { featuredPosition: null })
      } else {
        const used = news.map((article) => article.featuredPosition).filter((value): value is number => Boolean(value))
        const nextPosition = [1, 2, 3].find((position) => !used.includes(position))
        if (!nextPosition) {
          setError('首页轮播最多只能选择 3 篇资讯')
          return
        }
        await backend.updateAdminNews(item.id, { featuredPosition: nextPosition })
      }
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '精选设置失败')
    }
  }

  async function createExpert(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const slug = expertDraft.slug || slugify(expertDraft.name)
    if (!slug) return
    try {
      await backend.createAdminExpert({
        slug,
        name: expertDraft.name,
        title: expertDraft.title,
        organization: expertDraft.organization,
        specialties: expertDraft.specialties.split(/[，,]/).map((item) => item.trim()).filter(Boolean),
        priceAmount: Math.round(Number(expertDraft.price || 0) * 100),
        bio: expertDraft.bio,
        availabilityStatus: 'next-week',
        status: 'draft',
      })
      setSaved('专家草稿已保存')
      setExpertDraft({ name: '', slug: '', title: '', organization: '', specialties: '', price: '1200', bio: '' })
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家保存失败')
    }
  }

  return (
    <AdminShell title={currentMeta.title} description={currentMeta.description}>
      {saved && !isProductPanel && <div className="mb-3 border border-green-100 bg-green-50 px-3 py-2 text-sm font-bold text-green">{saved}</div>}
      <div className={`grid gap-4 ${isProductPanel || panel === 'news' ? '' : 'xl:grid-cols-[1fr_340px]'}`}>
        <div className="space-y-8">
          {migratedPanelHref && <div className="border border-line bg-white px-6 py-8">
            <div className="text-base font-extrabold text-ink">{currentMeta.title}</div>
            <div className="mt-2 text-sm font-bold leading-7 text-muted">{currentMeta.description}</div>
            <Link href={migratedPanelHref} className="mt-5 inline-flex h-9 items-center rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white hover:bg-brand">进入新模块</Link>
          </div>}

          {isProductPanel && <div className="border border-line bg-white">
            <div className="flex flex-col gap-3 border-b border-line px-4 py-3 md:flex-row md:items-center md:justify-between">
              <div>
                <div className="text-base font-extrabold text-ink">{currentMeta.title}</div>
                {error && <div className="mt-1 text-sm font-bold text-red-700">{error}</div>}
              </div>
              <div className="flex flex-wrap gap-2">
                {fixedProductType && (
                  <Link href={`/admin/products/catalog/new?type=${fixedProductType}`} className="grid h-8 w-8 place-items-center rounded-[4px] bg-ink text-white hover:bg-brand" aria-label={`新增${currentMeta.title}`}>
                    <Plus className="h-4 w-4" />
                  </Link>
                )}
                <button type="button" onClick={() => void reload()} className="grid h-8 w-8 place-items-center rounded-[4px] border border-line text-muted hover:border-brand hover:text-brand" aria-label="刷新">
                  <RefreshCw className="h-4 w-4" />
                </button>
                {!fixedProductType && ['全部', ...typeOptions.map((item) => item.value)].map((item) => {
                  const label = item === '全部' ? item : typeOptions.find((option) => option.value === item)?.label || item
                  return (
                    <button key={item} type="button" onClick={() => setType(item)} className={`rounded-[4px] border px-3 py-1.5 text-xs font-bold ${type === item ? 'border-brand bg-brand-light text-brand' : 'border-line text-muted hover:border-brand hover:text-brand'}`}>{label}</button>
                  )
                })}
              </div>
            </div>
            <div className="divide-y divide-line">
              {visibleProducts.map((item) => (
                <div key={item.id} className="grid gap-3 px-6 py-4 md:grid-cols-[80px_1fr_108px_140px] md:items-center">
                  <span className="rounded-[4px] bg-bg px-3 py-1 text-center text-xs font-bold text-muted">{typeOptions.find((option) => option.value === item.type)?.label}</span>
                  <div>
                    <div className="font-bold text-ink">{item.title}</div>
                    <div className="mt-1 text-xs text-muted">{item.slug} · ¥{yuan(item.priceAmount).toLocaleString()}</div>
                  </div>
                  <span className="text-xs font-bold text-brand">{statusLabel[item.status]}</span>
                  <div className="flex gap-2">
                    <button type="button" onClick={async () => { await backend.publishProduct(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">发布</button>
                    <button type="button" onClick={async () => { await backend.offlineProduct(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">下架</button>
                  </div>
                </div>
              ))}
            </div>
          </div>}

          {panel === 'coupons' && <div className="border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <div className="text-base font-extrabold text-ink">优惠码已迁移</div>
              <div className="mt-1 text-xs font-bold text-soft">优惠码新增、编辑、使用记录和试算已拆到独立模块。</div>
            </div>
            <div className="px-6 py-8">
              <Link href="/admin/coupons" className="inline-flex h-9 items-center rounded-[4px] bg-ink px-4 text-sm font-extrabold text-white hover:bg-brand">进入优惠码模块</Link>
            </div>
          </div>}

          {panel === 'news' && <div className="border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div>
                  <div className="text-base font-extrabold text-ink">资讯发布</div>
                  <div className="mt-1 text-xs font-bold text-soft">勾选且最多只能勾选 3 篇已发布资讯；列表固定按发布时间排序，不会因为编辑内容改变顺序。</div>
                </div>
                <Link href="/admin/content/news/new" className="grid h-8 w-8 place-items-center rounded-[4px] bg-ink text-white hover:bg-brand" aria-label="新增资讯">
                  <Plus className="h-4 w-4" />
                </Link>
              </div>
            </div>
            <div className="divide-y divide-line">
              {news.map((item) => (
                <div key={item.id} className="grid gap-3 px-6 py-4 lg:grid-cols-[52px_104px_1fr_96px_230px] lg:items-center">
                  <label className="grid h-9 w-9 place-items-center rounded-[4px] border border-line bg-white">
                    <input
                      type="checkbox"
                      checked={Boolean(item.featuredPosition)}
                      disabled={item.status !== 'published'}
                      onChange={(event) => void setFeaturedNews(item, event.target.checked)}
                      aria-label="设为首页精选资讯"
                    />
                  </label>
                  <span className="rounded-[4px] bg-bg px-3 py-1 text-center text-xs font-bold text-muted">{item.category}</span>
                  <div>
                    <div className="font-bold text-ink">{item.featuredPosition ? `精选 ${item.featuredPosition} · ` : ''}{item.title}</div>
                    <div className="mt-1 line-clamp-1 text-xs text-muted">{item.slug} · {item.authorName || '大连市大数据研究院'} · {item.publishedAt ? new Date(item.publishedAt).toLocaleDateString('zh-CN') : '未发布'}</div>
                  </div>
                  <span className="text-xs font-bold text-brand">{statusLabel[item.status]}</span>
                  <div className="flex flex-wrap gap-2">
                    <Link href={`/admin/content/news/${item.id}/edit`} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">编辑</Link>
                    {item.status !== 'published' && <button type="button" onClick={async () => { await backend.publishNews(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">上架</button>}
                    {item.status === 'published' && <button type="button" onClick={async () => { await backend.offlineNews(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">下架</button>}
                    <button type="button" onClick={async () => { await backend.draftNews(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">草稿</button>
                    <button type="button" onClick={async () => { if (!window.confirm('确定删除这篇资讯吗？')) return; await backend.deleteNews(item.id); await reload() }} className="rounded-[4px] border border-red-100 px-3 py-1.5 text-xs font-bold text-red-600 hover:border-red-300">
                      删除
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>}

          {panel === 'experts' && <div className="border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <div className="text-base font-extrabold text-ink">专家资源库</div>
              <div className="mt-1 text-xs font-bold text-soft">这里维护用户端专家平台和专家预约入口展示。</div>
            </div>
            <div className="divide-y divide-line">
              {experts.map((item) => (
                <div key={item.id} className="grid gap-3 px-6 py-4 lg:grid-cols-[1fr_110px_96px_140px] lg:items-center">
                  <div>
                    <div className="font-bold text-ink">{item.name} · {item.title}</div>
                    <div className="mt-1 line-clamp-1 text-xs text-muted">{item.organization} · {item.slug} · ¥{yuan(item.priceAmount).toLocaleString()}/小时</div>
                  </div>
                  <span className="text-xs font-bold text-muted">{availabilityLabel[item.availabilityStatus]}</span>
                  <span className="text-xs font-bold text-brand">{statusLabel[item.status]}</span>
                  <div className="flex gap-2">
                    <button type="button" onClick={async () => { await backend.publishExpert(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">发布</button>
                    <button type="button" onClick={async () => { await backend.offlineExpert(item.id); await reload() }} className="rounded-[4px] border border-line px-3 py-1.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">下线</button>
                  </div>
                </div>
              ))}
            </div>
          </div>}
        </div>

        {!isProductPanel && panel !== 'news' && panel === 'experts' && <aside className="h-fit space-y-4">
          <div className="rounded-[4px] border border-line bg-white p-4">
            <div className="text-base font-extrabold text-ink">新建专家草稿</div>
            <form className="mt-5 space-y-4" onSubmit={createExpert}>
              <input value={expertDraft.name} onChange={(event) => setExpertDraft((current) => ({ ...current, name: event.target.value }))} required placeholder="专家姓名" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={expertDraft.slug} onChange={(event) => setExpertDraft((current) => ({ ...current, slug: event.target.value }))} placeholder="slug，不填自动生成" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={expertDraft.title} onChange={(event) => setExpertDraft((current) => ({ ...current, title: event.target.value }))} placeholder="头衔" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={expertDraft.organization} onChange={(event) => setExpertDraft((current) => ({ ...current, organization: event.target.value }))} placeholder="所属机构" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={expertDraft.specialties} onChange={(event) => setExpertDraft((current) => ({ ...current, specialties: event.target.value }))} placeholder="擅长领域，用逗号分隔" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <input value={expertDraft.price} onChange={(event) => setExpertDraft((current) => ({ ...current, price: event.target.value }))} type="number" min="0" placeholder="咨询价（元/小时）" className="h-11 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" />
              <textarea value={expertDraft.bio} onChange={(event) => setExpertDraft((current) => ({ ...current, bio: event.target.value }))} rows={5} placeholder="专家简介" className="w-full rounded-[4px] border border-line p-3 text-sm outline-none focus:border-brand" />
              <button className="w-full rounded-[4px] border border-brand bg-white py-3 text-sm font-extrabold text-brand hover:bg-brand-light">保存专家草稿</button>
            </form>
          </div>
        </aside>}
      </div>
    </AdminShell>
  )
}

export default function AdminContentPage() {
  return (
    <Suspense fallback={<section className="grid min-h-screen place-items-center bg-[#f5f7fb] text-sm font-extrabold text-muted">正在加载内容管理...</section>}>
      <AdminContentInner />
    </Suspense>
  )
}
