import { Image, ScrollView, Swiper, SwiperItem, Text, View } from '@tarojs/components'
import { useDidShow, useTabItemTap } from '@tarojs/taro'
import { useState } from 'react'
import { CartDot, EmptyState, Page, ProductImage, SearchPill, Section, ServiceGlyph } from '@/components/ui'
import {
  backend,
  BRAND_LOGO_URL,
  BRAND_NAME,
  mapAgentProduct,
  mapCourseProduct,
  mapDataProduct,
  mapEventProduct,
  mapNewsArticle,
  type BackendRecommendationSlot,
  type BackendSiteHomeSlide
} from '@/api/backend'
import { serviceCategories } from '@/constants/services'
import { ensureLoggedIn } from '@/stores/storage'
import { go, toProduct, toServiceList } from '@/utils/nav'
import { tapLight, tapMedium } from '@/utils/feedback'
import type { NewsArticle, ServiceProduct } from '@/types'

function mapRecommendationProduct(slot: BackendRecommendationSlot): ServiceProduct | null {
  if (!slot.source || slot.status === 'hidden') return null
  if (slot.sourceType === 'course') return mapCourseProduct(slot.source as Parameters<typeof mapCourseProduct>[0])
  if (slot.sourceType === 'event') return mapEventProduct(slot.source as Parameters<typeof mapEventProduct>[0])
  if (slot.sourceType === 'data') return mapDataProduct(slot.source as Parameters<typeof mapDataProduct>[0])
  if (slot.sourceType === 'agent') return mapAgentProduct(slot.source as Parameters<typeof mapAgentProduct>[0])
  return null
}

export default function HomePage() {
  const [featuredProducts, setFeaturedProducts] = useState<ServiceProduct[]>([])
  const [articles, setArticles] = useState<NewsArticle[]>([])
  const [slides, setSlides] = useState<BackendSiteHomeSlide[]>([])
  useTabItemTap(tapMedium)

  useDidShow(() => {
    const user = ensureLoggedIn('/pages/home/index')
    if (!user) return
    Promise.all([
      backend.news(),
      backend.siteHome()
    ])
      .then(([newsData, siteHome]) => {
        const recommendationSlots = [
          ...(siteHome.recommendations?.courses || []),
          ...(siteHome.recommendations?.events || [])
        ]
        setFeaturedProducts(recommendationSlots.map(mapRecommendationProduct).filter((item): item is ServiceProduct => Boolean(item)).slice(0, 5))
        setArticles(newsData.items.map(mapNewsArticle).slice(0, 3))
        setSlides(siteHome.slides || [])
      })
      .catch(() => {
        setFeaturedProducts([])
        setArticles([])
        setSlides([])
      })
  })

  const backendSlides = slides
    .filter((item) => item.status === 'published' && item.imageUrl)
    .slice(0, 5)
  const visibleSlides = backendSlides

  return (
    <Page>
      <View className="top-row">
        <View className="top-brand">
          <Image className="top-logo" src={BRAND_LOGO_URL} mode="aspectFit" />
          <View style={{ flex: 1 }}>
            <Text className="top-title">{BRAND_NAME}</Text>
            <Text className="top-kicker">数字化服务平台</Text>
          </View>
        </View>
        <View onClick={() => go('/pages/cart/index')}>
          <CartDot />
        </View>
      </View>

      <View className="home-search-row">
        <SearchPill />
      </View>

      {visibleSlides.length ? (
        <Swiper className="hero-swiper" circular autoplay interval={3600} duration={450}>
          {visibleSlides.map((item) => (
            <SwiperItem key={item.id}>
              <View className="hero-slide" onClick={tapLight}>
                <Image className="hero-image" src={item.imageUrl} mode="aspectFill" />
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      ) : null}

      <Section title="常用服务">
        <View className="entry-grid">
          {serviceCategories.slice(0, 6).map((item) => (
            <View key={item.key} className="entry" onClick={() => toServiceList(item.key)}>
              <View className="entry-copy">
                <Text className="entry-text">{item.label}</Text>
              </View>
              <ServiceGlyph type={item.key} />
            </View>
          ))}
        </View>
      </Section>

      <Section title="推荐服务">
        <ScrollView scrollX className="h-scroll" enhanced showScrollbar={false}>
          {featuredProducts.map((item) => (
            <View key={item.id} className="compact-card" onClick={() => toProduct(item.id)}>
              <ProductImage className="compact-img" src={item.cover} />
              <View className="compact-body">
                <Text className="row-title">{item.title}</Text>
                <Text className="row-sub">{item.subtitle}</Text>
              </View>
            </View>
          ))}
          {featuredProducts.length === 0 ? <View className="empty-inline">暂无推荐服务</View> : null}
        </ScrollView>
      </Section>

      <Section title="新闻资讯">
        <View className="news-list clean">
          {articles.map((item) => (
            <View key={item.id} className="news-row" onClick={() => go(`/pages/news/detail/index?id=${item.id}`)}>
              <View style={{ flex: 1 }}>
                <Text className="news-title">{item.title}</Text>
              </View>
              <Text className="news-date">{item.date}</Text>
            </View>
          ))}
          {articles.length === 0 ? <EmptyState title="暂无已发布资讯" compact /> : null}
        </View>
      </Section>
    </Page>
  )
}
