import { ScrollView, Swiper, SwiperItem, Text, View } from '@tarojs/components'
import { useDidShow, useTabItemTap } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import { EmptyState, Page, ProductImage, SearchPill } from '@/components/ui'
import { backend, mapNewsArticle, type BackendNewsArticle, type BackendNewsCategory, type BackendRecommendationResponse, type BackendRecommendationSlot } from '@/api/backend'
import { ensureLoggedIn } from '@/stores/storage'
import { go } from '@/utils/nav'
import { tapMedium } from '@/utils/feedback'
import type { NewsArticle } from '@/types'

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

function isNewsRecommendationSlot(slot: BackendRecommendationSlot): slot is BackendRecommendationSlot & { sourceType: 'news'; source: BackendNewsArticle } {
  return slot.sourceType === 'news' && Boolean(slot.source)
}

export default function NewsPage() {
  const [articles, setArticles] = useState<NewsArticle[]>([])
  const [categories, setCategories] = useState<BackendNewsCategory[]>([])
  const [featuredArticles, setFeaturedArticles] = useState<NewsArticle[]>([])
  const [activeCategory, setActiveCategory] = useState('')
  const [loading, setLoading] = useState(true)
  useTabItemTap(tapMedium)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/news/index')
    if (!user) return
    setLoading(true)
    Promise.all([
      backend.news(),
      backend.newsCategories(),
      backend.siteRecommendations(['news.carousel']).catch((): BackendRecommendationResponse => ({ placements: {}, items: [] }))
    ])
      .then(([newsData, categoryData, recommendations]) => {
        const mappedArticles = newsData.items.map(mapNewsArticle)
        const activeCategories = (categoryData.items || []).filter((item) => item.status === 'active')
        const recommendationSlots = (recommendations.placements['news.carousel'] || []) as BackendRecommendationSlot[]
        const featured = recommendationSlots
          .filter((slot) => slot.status === 'active')
          .filter(isNewsRecommendationSlot)
          .map((slot) => mapNewsArticle(slot.source))
        setArticles(mappedArticles)
        setCategories(activeCategories)
        setFeaturedArticles(featured)
      })
      .catch(() => {
        setArticles([])
        setCategories([])
        setFeaturedArticles([])
      })
      .finally(() => setLoading(false))
  })

  const filteredArticles = useMemo(() => {
    if (!activeCategory) return articles
    const category = categories.find((item) => item.code === activeCategory)
    return articles.filter((article) => article.categoryCode === activeCategory || article.category === activeCategory || article.category === category?.name)
  }, [activeCategory, articles, categories])
  const activeCategoryName = categories.find((item) => item.code === activeCategory)?.name || '最新资讯'

  return (
    <Page title="新闻资讯" subtle="研究院动态与行业洞察">
      <View className="news-search-row">
        <SearchPill text="搜索资讯" placeholder="请输入资讯关键词" />
      </View>

      {featuredArticles.length ? (
        <Swiper className="news-featured-swiper" circular autoplay interval={3800} duration={420}>
          {featuredArticles.map((item) => (
            <SwiperItem key={item.id}>
              <View className="news-featured" onClick={() => go(`/pages/news/detail/index?id=${item.slug || item.id}`)}>
                {item.coverUrl ? <ProductImage src={item.coverUrl} className="news-featured-image" /> : null}
                <View className="news-featured-copy">
                  <Text className="news-featured-badge">{item.category}</Text>
                  <Text className="news-featured-title">{item.title}</Text>
                  <Text className="news-featured-summary">{item.summary}</Text>
                </View>
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      ) : null}

      <ScrollView scrollX className="category-scroll">
        <Text className={!activeCategory ? 'category-chip active' : 'category-chip'} onClick={() => setActiveCategory('')}>全部 {categoryCount(articles)}</Text>
        {categories.map((item) => (
          <Text key={item.code} className={activeCategory === item.code ? 'category-chip active' : 'category-chip'} onClick={() => setActiveCategory(item.code)}>
            {item.name} {categoryCount(articles, item)}
          </Text>
        ))}
      </ScrollView>

      <View className="news-section-head">
        <Text className="news-section-title">{activeCategoryName}</Text>
        <Text className="news-section-sub">{loading ? '正在同步后台资讯' : `共 ${filteredArticles.length} 条内容`}</Text>
      </View>

      <View className="news-list clean">
        {filteredArticles.map((item) => (
          <View key={item.id} className="news-row" onClick={() => go(`/pages/news/detail/index?id=${item.slug || item.id}`)}>
            {item.coverUrl ? <ProductImage src={item.coverUrl} className="news-thumb" /> : null}
            <View style={{ flex: 1 }}>
              <Text className="news-category">{item.category}</Text>
              <Text className="news-title">{item.title}</Text>
              <Text className="row-sub">{item.summary}</Text>
            </View>
            <Text className="news-date">{item.date}</Text>
          </View>
        ))}
        {filteredArticles.length === 0 && !loading ? <EmptyState title="暂无已发布资讯" compact /> : null}
      </View>
    </Page>
  )
}
