import { RichText, Text, View } from '@tarojs/components'
import { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { backend, mapNewsArticle } from '@/api/backend'
import { Page, ProductImage } from '@/components/ui'
import type { NewsArticle } from '@/types'

function contentToHtml(value = '') {
  const content = value.trim()
  if (!content) return ''
  if (/<[a-z][\s\S]*>/i.test(content)) return content
  return content
    .split(/\n{2,}|\|\|/)
    .map((item) => item.trim())
    .filter(Boolean)
    .map((item) => `<p>${item.replace(/\n/g, '<br/>')}</p>`)
    .join('')
}

export default function NewsDetailPage() {
  const [article, setArticle] = useState<NewsArticle | null>(null)

  useLoad((query) => {
    if (!query.id) return
    backend.newsDetail(query.id)
      .then((data) => setArticle(mapNewsArticle(data)))
      .catch(() => setArticle(null))
  })

  if (!article) {
    return (
      <Page title="资讯详情" subtle="新闻资讯">
        <View className="article-empty">
          <Text className="empty-inline">资讯加载中</Text>
        </View>
      </Page>
    )
  }

  const richContent = contentToHtml(article.content || article.summary)

  return (
    <Page title="资讯详情" subtle={`${article.category} · ${article.date}`}>
      <View className="article-body">
        {article.coverUrl ? <ProductImage src={article.coverUrl} className="product-image" /> : null}
        <Text className="article-title" style={{ marginTop: article.coverUrl ? '24px' : 0 }}>{article.title}</Text>
        <Text className="article-meta">{article.authorName || '大连市大数据研究院'}</Text>
        {article.summary ? <Text className="article-summary">{article.summary}</Text> : null}
        <RichText className="article-rich-text" nodes={richContent} />
      </View>
    </Page>
  )
}
