'use client'

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

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

function statusTone(status: string) {
  if (status === 'published') return 'text-green'
  if (status === 'offline') return 'text-muted'
  return 'text-amber-700'
}

function serviceTypeLabel(value?: string) {
  if (value === '研究报告') return '分析报告类'
  if (value === '表格数据') return '数据整理类'
  if (value === '政策数据库') return '政策资料类'
  if (value === '\u8d44\u6599\u5305') return '综合资料类'
  return value || '-'
}

function missingFields(item: BackendDataServiceCase) {
  const missing = []
  if (!item.coverUrl) missing.push('封面')
  if (!item.summary) missing.push('摘要')
  if (!item.caseGoal) missing.push('目标')
  if (!item.requestOutline) missing.push('需求')
  if (!item.deliveryOutline) missing.push('交付')
  return missing
}

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

  async function reload() {
    await backend.adminDataServiceCases()
      .then((result) => {
        setItems(result.items)
        setError('')
      })
      .catch((err) => setError(err instanceof Error ? err.message : '数据服务案例加载失败'))
  }

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

  const visibleItems = useMemo(() => {
    const lowerKeyword = keyword.trim().toLowerCase()
    return items.filter((item) => {
      if (status !== 'all' && item.status !== status) return false
      if (!lowerKeyword) return true
      return [item.title, item.slug, item.summary, item.category, ...(item.tags || [])].some((value) => String(value || '').toLowerCase().includes(lowerKeyword))
    })
  }, [items, keyword, status])

  async function changeStatus(id: string, action: 'publish' | 'offline' | 'delete') {
    try {
      if (action === 'publish') await backend.publishDataServiceCase(id)
      if (action === 'offline') await backend.offlineDataServiceCase(id)
      if (action === 'delete') {
        const confirmed = window.confirm('确定删除这个数据服务案例吗？删除后用户端不再展示，已有服务申请记录不受影响。')
        if (!confirmed) return
        await backend.deleteDataServiceCase(id)
      }
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败')
    }
  }

  return (
    <AdminShell title="数据服务案例" description="维护用户端数据服务案例、典型需求、交付说明和推荐展示；用户统一进入需求申请。">
      <div className="flex h-[calc(100vh-178px)] min-h-[620px] flex-col overflow-hidden">
        <div className="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 border border-line bg-white px-3 py-2">
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative">
              <Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-soft" />
              <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜标题 / 标签 / slug" className="h-8 w-56 rounded-[4px] border border-line pl-7 pr-2 text-xs font-bold" />
            </div>
            <select value={status} onChange={(event) => setStatus(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold text-muted">
              <option value="all">全部状态</option>
              <option value="published">已发布</option>
              <option value="draft">草稿</option>
              <option value="offline">已下线</option>
            </select>
            <span className="text-xs font-bold text-muted">共 {visibleItems.length} / {items.length} 条</span>
          </div>
          <Link href="/admin/data-service/cases/new" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">
            <Plus className="h-3.5 w-3.5" />
            新增案例
          </Link>
        </div>
        {error && <div className="mb-3 shrink-0 border border-red-100 bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}

        <div className="min-h-0 flex-1 overflow-auto border border-line bg-white">
          <div className="min-w-[1080px]">
            <div className="grid grid-cols-[minmax(260px,1fr)_120px_220px_120px_90px_190px] border-b border-line px-3 py-2 text-[11px] font-extrabold text-soft">
              <span>案例</span><span>服务归类</span><span>标签 / 完整度</span><span>推荐 / 排序</span><span>状态</span><span>操作</span>
            </div>
            {visibleItems.map((item) => {
              const missing = missingFields(item)
              return (
                <div key={item.id} className="grid grid-cols-[minmax(260px,1fr)_120px_220px_120px_90px_190px] items-center border-b border-line px-3 py-2 text-sm 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-soft">{item.slug}</div>
                  </div>
                  <span className="text-xs font-bold text-muted">{serviceTypeLabel(item.serviceType || item.category)}</span>
                  <div className="min-w-0">
                    <div className="truncate text-xs font-bold text-muted">{(item.industryTags || item.tags || []).join('、') || '-'}</div>
                    <div className={`mt-0.5 truncate text-[11px] font-extrabold ${missing.length ? 'text-amber-700' : 'text-green'}`}>
                      {missing.length ? `缺：${missing.join('、')}` : '完整'}
                    </div>
                  </div>
                  <span className="text-xs font-bold text-muted">{item.featuredPosition ? '推荐' : '普通'} · {item.sortOrder}</span>
                  <span className={`text-xs font-extrabold ${statusTone(item.status)}`}>{statusLabel(item.status)}</span>
                  <div className="flex flex-wrap items-center gap-2">
                    <Link href={`/admin/data-service/cases/${item.id}/edit`} className="text-xs font-extrabold text-brand">编辑</Link>
                    <Link href={`/data/${item.slug}`} target="_blank" className="inline-flex items-center gap-1 text-xs font-extrabold text-muted hover:text-brand">
                      <ExternalLink className="h-3 w-3" />
                      预览
                    </Link>
                    {item.status !== 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'publish')} className="text-xs font-extrabold text-ink">发布</button>}
                    {item.status === 'published' && <button type="button" onClick={() => void changeStatus(item.id, 'offline')} className="text-xs font-extrabold text-ink">下线</button>}
                    <button type="button" onClick={() => void changeStatus(item.id, 'delete')} className="text-xs font-extrabold text-red-600">删除</button>
                  </div>
                </div>
              )
            })}
            {!visibleItems.length && !error && <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无匹配的数据服务案例</div>}
          </div>
        </div>
      </div>
    </AdminShell>
  )
}
