'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { Plus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendCourseProduct, yuan } from '@/lib/backend'

function safeCents(value: unknown) {
  return Number.isFinite(Number(value)) ? Number(value) : 0
}

function statusLabel(status: string) {
  if (status === 'published') return '已发布'
  if (status === 'offline') return '已下架'
  return '草稿'
}

function formatStart(value: string | null) {
  if (!value) return '随时学习'
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function accessLabel(access: 'closed' | 'free' | 'paid', priceAmount: number) {
  if (access === 'closed') return '不可购买'
  if (access === 'free') return '免费'
  return `¥${yuan(safeCents(priceAmount))}`
}

function accessSummary(item: BackendCourseProduct) {
  return [
    `注册 ${accessLabel(item.registeredAccess, item.registeredPriceAmount)}`,
    `初级 ${accessLabel(item.juniorAccess, item.juniorPriceAmount)}`,
    `高级 ${accessLabel(item.seniorAccess, item.seniorPriceAmount)}`,
  ].join(' / ')
}

function completionIssues(item: BackendCourseProduct) {
  const issues: string[] = []
  if (!item.coverUrl) issues.push('缺封面')
  if (!item.instructor) issues.push('缺讲师')
  if (!item.summary) issues.push('缺摘要')
  if (!item.outcomes?.length) issues.push('缺收获')
  if (!item.lessonModules?.length && !item.modules?.length) issues.push('缺目录')
  if (['registered', 'junior', 'senior'].some((level) => {
    const accessKey = `${level}Access` as 'registeredAccess' | 'juniorAccess' | 'seniorAccess'
    const priceKey = `${level}PriceAmount` as 'registeredPriceAmount' | 'juniorPriceAmount' | 'seniorPriceAmount'
    return item[accessKey] === 'paid' && safeCents(item[priceKey]) <= 0
  })) issues.push('缺价格')
  return issues
}

export default function AdminCourseProductsPage() {
  const [items, setItems] = useState<BackendCourseProduct[]>([])
  const [keyword, setKeyword] = useState('')
  const [status, setStatus] = useState('all')
  const [format, setFormat] = useState('all')
  const [error, setError] = useState('')

  async function reload() {
    await backend.adminCourseProducts().then((result) => {
      setItems(result.items)
      setError('')
    }).catch((err) => setError(err instanceof Error ? err.message : '课程商品加载失败'))
  }

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

  async function changeStatus(id: string, action: 'publish' | 'offline' | 'delete') {
    if (action === 'publish') await backend.publishCourseProduct(id)
    if (action === 'offline') await backend.offlineCourseProduct(id)
    if (action === 'delete') {
      const confirmed = window.confirm('确定删除这个课程商品吗？删除后用户端不再展示，已有关联订单仍保留快照。')
      if (!confirmed) return
      await backend.deleteCourseProduct(id)
    }
    await reload()
  }

  const formats = useMemo(() => Array.from(new Set(items.map((item) => item.courseFormat).filter(Boolean))), [items])
  const filteredItems = useMemo(() => {
    const query = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const matchKeyword = !query || [item.title, item.slug, item.direction, item.instructor, item.summary].some((value) => String(value || '').toLowerCase().includes(query))
      const matchStatus = status === 'all' || item.status === status
      const matchFormat = format === 'all' || item.courseFormat === format
      return matchKeyword && matchStatus && matchFormat
    })
  }, [format, items, keyword, status])

  return (
    <AdminShell title="课程产品" description="维护课程 SKU、价格权限、课程内容和个人中心学习权益。">
      <div className="space-y-2">
        <div className="grid gap-2 border border-line bg-white p-2 lg:grid-cols-[1fr_140px_140px_auto]">
          <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜索课程、方向、讲师" className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand" />
          <select value={format} onChange={(event) => setFormat(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            <option value="all">全部形式</option>
            {formats.map((item) => <option key={item} value={item}>{item}</option>)}
          </select>
          <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-8 border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            <option value="all">全部状态</option>
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
            <option value="offline">已下架</option>
          </select>
          <Link href="/admin/products/courses/new" className="inline-flex h-8 items-center justify-center gap-1.5 bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">
            <Plus className="h-3.5 w-3.5" />
            新增课程
          </Link>
        </div>
        <div className="border border-line bg-white">
          <div className="grid grid-cols-[minmax(220px,1fr)_88px_220px_108px_80px_90px_80px_190px] border-b border-line px-3 py-2 text-xs font-extrabold text-soft">
            <span>课程</span><span>形式</span><span>价格权限</span><span>开课</span><span>报名</span><span>完整度</span><span>状态</span><span>操作</span>
          </div>
          <div className="max-h-[calc(100vh-178px)] overflow-y-auto">
            {error && <div className="px-3 py-3 text-sm font-bold text-red-700">{error}</div>}
            {filteredItems.length === 0 && !error && <div className="px-3 py-10 text-center text-sm font-bold text-muted">暂无匹配课程</div>}
            {filteredItems.map((item) => {
              const issues = completionIssues(item)
              return (
                <div key={item.id} className="grid grid-cols-[minmax(220px,1fr)_88px_220px_108px_80px_90px_80px_190px] items-center border-b border-line px-3 py-2 text-xs hover:bg-bg">
                  <div className="min-w-0">
                    <div className="truncate font-extrabold text-ink">{item.title}</div>
                    <div className="mt-0.5 truncate text-[11px] font-bold text-muted">{item.slug} · {item.direction || '未设方向'} · {item.instructor || '未设讲师'}</div>
                  </div>
                  <span className="font-bold text-muted">{item.courseFormat || '未设'}</span>
                  <span className="font-bold leading-5 text-ink">{accessSummary(item)}</span>
                  <span className="font-bold text-muted">{formatStart(item.startsAt)}</span>
                  <span className="font-bold text-muted">{item.courseFormat === '线下培训' ? `${item.registeredCount || 0}/${item.capacity || '不限'}` : '-'}</span>
                  <span className={`font-extrabold ${issues.length ? 'text-red-600' : 'text-brand'}`}>{issues.length ? issues.slice(0, 2).join('、') : '完整'}</span>
                  <span className="font-extrabold text-brand">{statusLabel(item.status)}</span>
                  <div className="flex flex-wrap gap-x-2 gap-y-1">
                    <Link href={`/admin/products/courses/${item.id}/edit`} className="font-extrabold text-brand">编辑</Link>
                    <Link href={`/admin/products/courses/${item.id}/detail`} className="font-extrabold text-ink">详情</Link>
                    {item.status !== 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'publish')} className="font-extrabold text-ink">上架</button>}
                    {item.status === 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'offline')} className="font-extrabold text-ink">下架</button>}
                    <button type="button" onClick={() => void changeStatus(item.id, 'delete')} className="font-extrabold text-red-600">删除</button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </AdminShell>
  )
}
