'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 BackendAgentProduct, yuan } from '@/lib/backend'
import type { CourseAccessState } from '@/types'

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

function normalizeAccessState(value: unknown): CourseAccessState {
  if (value === 'closed' || value === 'free' || value === 'paid') return value
  return 'paid'
}

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

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

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

function completionIssues(item: BackendAgentProduct) {
  const issues: string[] = []
  if (!item.coverUrl) issues.push('缺封面')
  if (!item.summary) issues.push('缺摘要')
  if (!item.detailDescription) issues.push('缺详情')
  if (!item.deliveryNote) issues.push('缺交付')
  if (!item.scenarioTags?.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 normalizeAccessState(item[accessKey]) === 'paid' && safeCents(item[priceKey]) <= 0
  })) issues.push('缺价格')
  return issues
}

export default function AdminAgentProductsPage() {
  const [items, setItems] = useState<BackendAgentProduct[]>([])
  const [keyword, setKeyword] = useState('')
  const [status, setStatus] = useState('all')
  const [quotaOnly, setQuotaOnly] = useState(false)
  const [error, setError] = useState('')

  async function reload() {
    const result = await backend.adminAgentProducts()
    setItems(result.items)
  }

  async function changeAgentStatus(id: string, action: 'publish' | 'offline' | 'draft') {
    try {
      if (action === 'publish') await backend.publishAgentProduct(id)
      if (action === 'offline') await backend.offlineAgentProduct(id)
      if (action === 'draft') await backend.draftAgentProduct(id)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败')
    }
  }

  async function deleteProduct(id: string) {
    if (!window.confirm('确认删除该智能体商品？删除后不可恢复。')) return
    try {
      await backend.deleteAgentProduct(id)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除失败')
    }
  }

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        const result = await backend.adminAgentProducts()
        if (mounted) setItems(result.items)
      } catch (err) {
        if (mounted) setError(err instanceof Error ? err.message : '智能体产品加载失败')
      }
    })()
    return () => {
      mounted = false
    }
  }, [])

  const filteredItems = useMemo(() => {
    const query = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const matchKeyword = !query || [item.title, item.slug, item.summary, item.detailDescription, ...(item.scenarioTags || [])].some((value) => String(value || '').toLowerCase().includes(query))
      const matchStatus = status === 'all' || item.status === status
      const matchQuota = !quotaOnly || Boolean(item.redeemableByMember)
      return matchKeyword && matchStatus && matchQuota
    })
  }, [items, keyword, quotaOnly, 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_auto_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={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>
          <label className="inline-flex h-8 items-center gap-2 border border-line px-3 text-xs font-extrabold text-ink">
            <input type="checkbox" checked={quotaOnly} onChange={(event) => setQuotaOnly(event.target.checked)} />
            仅额度兑换
          </label>
          <Link href="/admin/products/agents/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)_220px_90px_90px_80px_150px] 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>
          </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)_220px_90px_90px_80px_150px] 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.scenarioTags || []).join(' / ') || '未设标签'}</div>
                  </div>
                  <div>
                    <div className="font-bold text-ink">{accessSummary(item)}</div>
                    <div className="mt-0.5 text-[11px] font-bold text-muted">基础价：¥{yuan(safeCents(item.priceAmount))}</div>
                  </div>
                  <span className="font-extrabold text-muted">{item.redeemableByMember ? '可兑换' : '-'}</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/agents/${item.id}/edit`} className="font-extrabold text-brand">编辑</Link>
                    {item.status !== 'published' && <button type="button" onClick={() => void changeAgentStatus(item.id, 'publish')} className="font-extrabold text-ink">发布</button>}
                    {item.status === 'published' && <button type="button" onClick={() => void changeAgentStatus(item.id, 'offline')} className="font-extrabold text-ink">下架</button>}
                    <button type="button" onClick={() => void deleteProduct(item.id)} className="font-extrabold text-[#b91c1c]">删除</button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </AdminShell>
  )
}
