'use client'

import Link from 'next/link'
import { ArrowRight } from 'lucide-react'
import { useMemo, useState } from 'react'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import type { BackendNewsCategory } from '@/lib/backend'
import type { NewsArticle } from '@/types'

function formatDate(value: string) {
  const [year, month, day] = value.slice(0, 10).split('-')
  return `${year}.${month}.${day}`
}

function categoryCount(articles: NewsArticle[], category: BackendNewsCategory | null) {
  if (!category) return articles.length
  return category.articleCount ?? articles.filter((article) => article.categoryCode === category.code || article.category === category.name).length
}

export function NewsListFilter({ articles, categories }: { articles: NewsArticle[]; categories: BackendNewsCategory[] }) {
  const [activeCategory, setActiveCategory] = useState('')
  const visibleCategories = categories.filter((item) => item.status === 'active')
  const filteredArticles = useMemo(() => {
    if (!activeCategory) return articles
    return articles.filter((article) => article.categoryCode === activeCategory || article.category === activeCategory)
  }, [activeCategory, articles])

  return (
    <section className="bg-bg py-12">
      <div className="mx-auto grid max-w-[1280px] gap-10 px-6 lg:grid-cols-[260px_1fr]">
        <aside className="h-fit border-y border-line bg-white py-4 lg:sticky lg:top-28">
          <div className="px-5 pb-3 text-sm font-extrabold text-ink">资讯栏目</div>
          <div className="flex gap-2 overflow-x-auto px-5 pb-2 lg:grid lg:gap-0 lg:overflow-visible lg:px-0 lg:pb-0">
            {[null, ...visibleCategories].map((category) => {
              const code = category?.code || ''
              const name = category?.name || '全部'
              const isActive = activeCategory === code

              return (
                <button
                  key={code || 'all'}
                  type="button"
                  onClick={() => setActiveCategory(code)}
                  className={`group flex h-10 shrink-0 items-center justify-between gap-3 rounded-full px-4 text-left text-sm font-bold transition-colors lg:h-auto lg:rounded-none lg:border-t lg:border-line lg:px-5 lg:py-4 ${
                    isActive ? 'bg-brand-light text-brand' : 'bg-bg text-text-body hover:bg-brand-light hover:text-brand lg:bg-white'
                  }`}
                >
                  <span>{name}</span>
                  <span className={`text-xs ${isActive ? 'text-brand' : 'text-soft group-hover:text-brand'}`}>{categoryCount(articles, category)}</span>
                </button>
              )
            })}
          </div>
        </aside>

        <div className="space-y-10">
          <div className="flex items-end justify-between gap-6">
            <div>
              <h2 className="text-2xl font-extrabold text-ink">{!activeCategory ? '最新资讯' : visibleCategories.find((item) => item.code === activeCategory)?.name || activeCategory}</h2>
              <p className="mt-3 text-sm leading-7 text-muted">
                {!activeCategory ? '研究院动态与行业洞察集中呈现。' : `共 ${filteredArticles.length} 条内容。`}
              </p>
            </div>
          </div>

          {filteredArticles.length > 0 ? (
            <div className="border-y border-line bg-white">
              {filteredArticles.map((article) => (
                <Link
                  key={article.id}
                  href={`/news/${article.slug}`}
                  className="group grid gap-5 border-b border-line px-5 py-6 last:border-b-0 md:grid-cols-[220px_1fr_auto] md:items-center"
                >
                  {article.coverUrl ? <div className="h-36 w-full bg-cover bg-center" style={{ backgroundImage: `url(${article.coverUrl})` }} /> : <ImagePlaceholder label={`${article.title}配图`} className="h-36 w-full" />}
                  <div>
                    <div className="text-xs font-bold text-muted">{formatDate(article.publishedAt)}</div>
                    <h3 className="mt-3 text-xl font-extrabold leading-snug text-ink transition-colors group-hover:text-brand">
                      {article.title}
                    </h3>
                    <p className="mt-3 line-clamp-2 text-sm leading-7 text-muted">{article.summary}</p>
                  </div>
                  <div className="hidden h-10 w-10 place-items-center rounded-[4px] border border-line text-muted transition-colors group-hover:border-brand group-hover:text-brand md:grid">
                    <ArrowRight className="h-4 w-4" />
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <div className="border-y border-line bg-white px-6 py-16 text-center">
              <div className="text-lg font-extrabold text-ink">暂无资讯</div>
              <p className="mt-2 text-sm text-muted">当前栏目暂未发布内容，请切换其他栏目查看。</p>
              <button
                type="button"
                onClick={() => setActiveCategory('')}
                className="mt-5 rounded-[4px] bg-brand px-5 py-2.5 text-sm font-bold text-white"
              >
                查看全部
              </button>
            </div>
          )}
        </div>
      </div>
    </section>
  )
}
