'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { Edit3, Plus, RefreshCw, Search, Star, Trash2 } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendNewsArticle, type BackendNewsCategory } from '@/lib/backend'

const statusLabel: Record<string, string> = {
  draft: '草稿',
  published: '已发布',
  offline: '已下架',
}

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

export default function AdminNewsPage() {
  const [items, setItems] = useState<BackendNewsArticle[]>([])
  const [categories, setCategories] = useState<BackendNewsCategory[]>([])
  const [status, setStatusFilter] = useState('')
  const [category, setCategory] = useState('')
  const [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  async function reload() {
    setLoading(true)
    try {
      const [newsResult, categoryResult] = await Promise.all([
        backend.adminNews(),
        backend.adminNewsCategories(),
      ])
      setItems(newsResult.items)
      setCategories(categoryResult.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '资讯加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  const filtered = useMemo(() => {
    const query = keyword.trim().toLowerCase()
    return items.filter((item) => {
      const statusMatched = !status || item.status === status
      const categoryMatched = !category || item.categoryCode === category || item.category === category
      const keywordMatched = !query || [item.title, item.slug, item.summary, item.authorName].some((value) => String(value || '').toLowerCase().includes(query))
      return statusMatched && categoryMatched && keywordMatched
    })
  }, [category, items, keyword, status])

  const stats = useMemo(() => ({
    total: items.length,
    published: items.filter((item) => item.status === 'published').length,
    draft: items.filter((item) => item.status === 'draft').length,
    featured: items.filter((item) => item.featuredPosition).length,
  }), [items])

  async function setFeatured(item: BackendNewsArticle, checked: boolean) {
    try {
      if (!checked) {
        await backend.updateAdminNews(item.id, { featuredPosition: null })
      } else {
        if (item.status !== 'published') {
          setError('只有已发布资讯可以进入轮播精选')
          return
        }
        const used = items.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 changeNewsStatus(id: string, next: 'published' | 'offline' | 'draft') {
    try {
      if (next === 'published') await backend.publishNews(id)
      if (next === 'offline') await backend.offlineNews(id)
      if (next === 'draft') await backend.draftNews(id)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '状态更新失败')
    }
  }

  async function removeNews(item: BackendNewsArticle) {
    if (!window.confirm(`确定删除资讯「${item.title}」吗？`)) return
    try {
      await backend.deleteNews(item.id)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除失败')
    }
  }

  return (
    <AdminShell
      title="资讯发布"
      description="发布资讯、维护首页/资讯页轮播精选，并按分类和状态快速筛选。"
      topbarMetrics={[
        { label: '全部资讯', value: stats.total },
        { label: '已发布', value: stats.published },
        { label: '草稿', value: stats.draft },
        { label: '轮播精选', value: `${stats.featured}/3` },
      ]}
    >
      <div className="grid h-[calc(100vh-144px)] min-h-[560px] grid-rows-[auto_1fr] gap-3 overflow-hidden">
        <section className="border border-line bg-white px-3 py-3">
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative min-w-[220px] flex-1">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-soft" />
              <input value={keyword} onChange={(event) => setKeyword(event.target.value)} className="h-8 w-full rounded-[4px] border border-line pl-8 pr-3 text-xs font-bold outline-none focus:border-brand" placeholder="搜标题、摘要、作者、slug" />
            </div>
            <select value={status} onChange={(event) => setStatusFilter(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold">
              <option value="">全部状态</option>
              <option value="published">已发布</option>
              <option value="draft">草稿</option>
              <option value="offline">已下架</option>
            </select>
            <select value={category} onChange={(event) => setCategory(event.target.value)} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold">
              <option value="">全部分类</option>
              {categories.map((item) => <option key={item.code} value={item.code}>{item.name}</option>)}
            </select>
            <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-3.5 w-3.5" />
            </button>
            <Link href="/admin/news/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="mt-2 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}
        </section>

        <section className="min-h-0 overflow-hidden border border-line bg-white">
          <div className="grid grid-cols-[56px_96px_1fr_96px_112px_220px] border-b border-line bg-bg px-3 py-2 text-[11px] font-extrabold text-soft">
            <span>精选</span><span>分类</span><span>标题</span><span>状态</span><span>发布</span><span>操作</span>
          </div>
          <div className="h-full overflow-auto pb-8">
            {loading && <div className="px-4 py-10 text-sm font-bold text-muted">正在加载资讯...</div>}
            {!loading && filtered.length === 0 && <div className="px-4 py-10 text-sm font-bold text-muted">暂无匹配资讯</div>}
            {!loading && filtered.map((item) => (
              <div key={item.id} className="grid grid-cols-[56px_96px_1fr_96px_112px_220px] items-center gap-0 border-b border-line px-3 py-2 text-sm hover:bg-bg/70">
                <button type="button" onClick={() => void setFeatured(item, !item.featuredPosition)} className={`grid h-7 w-7 place-items-center rounded-[4px] border ${item.featuredPosition ? 'border-brand bg-brand-light text-brand' : 'border-line text-soft hover:border-brand hover:text-brand'}`} aria-label="切换轮播精选">
                  <Star className="h-3.5 w-3.5" fill={item.featuredPosition ? 'currentColor' : 'none'} />
                </button>
                <span className="truncate text-xs font-bold text-muted">{item.category}</span>
                <div className="min-w-0 pr-3">
                  <div className="truncate font-extrabold text-ink">{item.featuredPosition ? `精选 ${item.featuredPosition} · ` : ''}{item.title}</div>
                  <div className="mt-0.5 truncate text-[11px] font-bold text-soft">{item.slug} · {item.authorName || '未填写作者'}</div>
                </div>
                <span className="text-xs font-extrabold text-brand">{statusLabel[item.status] || item.status}</span>
                <span className="text-xs font-bold text-muted">{formatDate(item.publishedAt)}</span>
                <div className="flex flex-wrap items-center gap-1.5">
                  <Link href={`/admin/news/${item.id}/edit`} className="grid h-7 w-7 place-items-center rounded-[4px] border border-line text-muted hover:border-brand hover:text-brand" aria-label="编辑">
                    <Edit3 className="h-3.5 w-3.5" />
                  </Link>
                  {item.status !== 'published' && <button type="button" onClick={() => void changeNewsStatus(item.id, 'published')} className="h-7 rounded-[4px] border border-line px-2 text-[11px] font-extrabold text-muted hover:border-brand hover:text-brand">发布</button>}
                  {item.status === 'published' && <button type="button" onClick={() => void changeNewsStatus(item.id, 'offline')} className="h-7 rounded-[4px] border border-line px-2 text-[11px] font-extrabold text-muted hover:border-brand hover:text-brand">下架</button>}
                  {item.status !== 'draft' && <button type="button" onClick={() => void changeNewsStatus(item.id, 'draft')} className="h-7 rounded-[4px] border border-line px-2 text-[11px] font-extrabold text-muted hover:border-brand hover:text-brand">草稿</button>}
                  <button type="button" onClick={() => void removeNews(item)} className="grid h-7 w-7 place-items-center rounded-[4px] border border-red-100 text-red-600 hover:border-red-300" aria-label="删除">
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>
    </AdminShell>
  )
}
