import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import Link from 'next/link'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { ImagePlaceholder } from '@/components/shared/ImagePlaceholder'
import { getFeaturedNewsArticles, getNewsArticle, getNewsArticles } from '@/lib/server-news'

export async function generateStaticParams() {
  const newsArticles = await getNewsArticles()
  return newsArticles.map((n) => ({ slug: n.slug }))
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const article = await getNewsArticle(slug)
  if (!article) return {}
  return { title: article.title }
}

export default async function NewsDetailPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const [article, newsArticles, featuredNewsArticles] = await Promise.all([getNewsArticle(slug), getNewsArticles(), getFeaturedNewsArticles()])
  if (!article) notFound()

  const currentIndex = newsArticles.findIndex((n) => n.id === article.id)
  const previous = currentIndex > 0 ? newsArticles[currentIndex - 1] : null
  const next = currentIndex >= 0 && currentIndex < newsArticles.length - 1 ? newsArticles[currentIndex + 1] : null
  const relatedByAdmin = (article.relatedArticleIds || [])
    .map((id) => newsArticles.find((item) => item.id === id))
    .filter((item): item is (typeof newsArticles)[number] => Boolean(item))
  const related = relatedByAdmin.length ? relatedByAdmin : newsArticles.filter((n) => n.id !== article.id).slice(0, 3)
  const featuredFocus = featuredNewsArticles.filter((item) => item.id !== article.id).slice(0, 3)
  const htmlContent = (article.content || '').includes('<')
    ? article.content || ''
    : (article.content || '').split('||').map((item) => item.trim()).filter(Boolean).map((item) => `<p>${item}</p>`).join('')

  return (
    <>
      <section className="bg-white py-12">
        <div className="mx-auto max-w-[960px] px-6">
          <div className="mb-8 flex items-center gap-2 text-sm font-bold text-soft">
            <Link href="/news" className="text-muted hover:text-brand">新闻资讯</Link>
            <span>/</span>
            <span className="line-clamp-1">{article.title}</span>
          </div>

          <article>
            <header className="border-b border-line pb-8">
              <h1 className="text-3xl font-extrabold leading-tight text-ink md:text-[42px]">{article.title}</h1>
              <div className="mt-5 text-sm text-soft">{new Date(article.publishedAt).toLocaleDateString('zh-CN')} · {article.authorName || '大连市大数据研究院'}</div>
            </header>

            {article.coverUrl ? <div className="my-8 w-full rounded-[4px] bg-cover bg-center" style={{ aspectRatio: '16/7', backgroundImage: `url(${article.coverUrl})` }} /> : <ImagePlaceholder label={article.title} className="my-8 w-full rounded-[4px]" aspectRatio="16/7" />}

            <div className="mx-auto max-w-[760px]">
              <p className="border-l-4 border-brand bg-bg px-5 py-4 text-base font-bold leading-8 text-ink">
                {article.summary}
              </p>
              <div className="mt-8 space-y-6 text-[15px] leading-8 text-text-body [&_img]:my-6 [&_img]:w-full [&_img]:rounded-[4px] [&_p]:mb-6" dangerouslySetInnerHTML={{ __html: htmlContent }} />

              {featuredFocus.length ? <div className="mt-10 border-y border-line py-6">
                <div className="text-sm font-extrabold text-ink">延伸关注</div>
                <div className="mt-4 grid gap-3 text-sm leading-7 text-muted md:grid-cols-3">
                  {featuredFocus.map((item) => (
                    <Link key={item.id} href={`/news/${item.slug}`} className="group rounded-[4px] border border-line bg-bg p-4 hover:border-brand hover:bg-white">
                      <div className="text-xs font-extrabold text-brand">{item.category}</div>
                      <div className="mt-2 line-clamp-2 font-extrabold leading-6 text-ink group-hover:text-brand">{item.title}</div>
                    </Link>
                  ))}
                </div>
              </div> : null}
            </div>
          </article>

          <div className="mt-10 grid gap-4 border-t border-line pt-8 md:grid-cols-2">
            {previous ? (
              <Link href={`/news/${previous.slug}`} className="group rounded-[4px] border border-line p-5 hover:border-brand">
                <div className="mb-3 inline-flex items-center gap-2 text-xs font-bold text-soft group-hover:text-brand">
                  <ArrowLeft className="h-3.5 w-3.5" />
                  上一篇
                </div>
                <div className="line-clamp-2 text-sm font-extrabold leading-6 text-ink group-hover:text-brand">{previous.title}</div>
              </Link>
            ) : <div />}
            {next ? (
              <Link href={`/news/${next.slug}`} className="group rounded-[4px] border border-line p-5 text-right hover:border-brand">
                <div className="mb-3 inline-flex items-center gap-2 text-xs font-bold text-soft group-hover:text-brand">
                  下一篇
                  <ArrowRight className="h-3.5 w-3.5" />
                </div>
                <div className="line-clamp-2 text-sm font-extrabold leading-6 text-ink group-hover:text-brand">{next.title}</div>
              </Link>
            ) : <div />}
          </div>
        </div>
      </section>

      <section className="bg-bg py-12">
        <div className="mx-auto max-w-[960px] px-6">
          <h2 className="mb-6 text-xl font-extrabold text-ink">相关文章</h2>
          <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
            {related.map((n) => (
              <Link
                key={n.id}
                href={`/news/${n.slug}`}
                className="group rounded-[4px] border border-line bg-white p-4 transition-all hover:border-brand hover:shadow-sm"
              >
                <h3 className="mb-2 line-clamp-2 text-sm font-extrabold leading-snug text-ink transition-colors group-hover:text-brand">{n.title}</h3>
                <div className="text-xs text-soft">{new Date(n.publishedAt).toLocaleDateString('zh-CN')}</div>
              </Link>
            ))}
          </div>
        </div>
      </section>
    </>
  )
}
