import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listCmsArticle } from '@/api/cms/cmsArticle'
import type { CmsArticle } from '@/api/cms/cmsArticle/model'
import EmptyState from '@/components/common/EmptyState'
import { useScrollHeight } from '@/hooks/useScrollHeight'

definePageConfig({
  navigationBarTitleText: '活动列表',
})

const ArticleListPage: React.FC = () => {
  const [articles, setArticles] = useState<CmsArticle[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const scrollHeight = useScrollHeight(44)


  const type = (Taro.getCurrentInstance().router?.params as any)?.type || 'activity'

  useEffect(() => {
    fetchArticles()
  }, [])

  const fetchArticles = async (loadMore = false) => {
    try {
      const currentPage = loadMore ? page + 1 : 1
      const data = await listCmsArticle({
        category: type === 'activity' ? 'activity' : 'notice',
        status: 1,
        page: currentPage,
        limit: 10,
      })

      if (data) {
        if (loadMore) {
          setArticles(prev => [...prev, ...data])
          setPage(currentPage)
        } else {
          setArticles(data)
        }
        setHasMore(data.length >= 10)
      }
    } catch (e) {
      console.error('获取文章列表失败:', e)
    } finally {
      setLoading(false)
    }
  }

  const handleLoadMore = () => {
    if (!hasMore || loading) return
    fetchArticles(true)
  }

  const handleArticleClick = (id: number) => {
    Taro.navigateTo({ url: `/pages/index/article-detail?id=${id}` })
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView
        scrollY
        style={{ height: scrollHeight }}
        onScrollToLower={handleLoadMore}
      >
        {loading ? (
          <View className='flex items-center justify-center py-10'>
            <Text className='text-gray-400'>加载中...</Text>
          </View>
        ) : articles.length === 0 ? (
          <EmptyState text='暂无活动' />
        ) : (
          <View className='p-3'>
            {articles.map(item => (
              <View
                key={item.id}
                className='bg-white rounded-lg mb-3 overflow-hidden'
                onClick={() => handleArticleClick(item.id)}
              >
                {item.coverImage && (
                  <Image
                    className='w-full'
                    src={item.coverImage}
                    mode='aspectFill'
                    style={{ height: '160px' }}
                  />
                )}
                <View className='p-3'>
                  <Text className='text-base font-medium text-gray-800 block mb-1'>
                    {item.title}
                  </Text>
                  {item.summary && (
                    <Text className='text-sm text-gray-500 mb-2 block' numberOfLines={2}>
                      {item.summary}
                    </Text>
                  )}
                  <View className='flex justify-between items-center'>
                    <Text className='text-xs text-gray-400'>
                      {item.createTime}
                    </Text>
                    {item.isHot && (
                      <View className='px-2 py-0 bg-red-500 rounded-full'>
                        <Text className='text-xs text-white'>热门</Text>
                      </View>
                    )}
                  </View>
                </View>
              </View>
            ))}
            {hasMore && (
              <View className='py-3 text-center'>
                <Text className='text-gray-400 text-sm'>加载更多...</Text>
              </View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default ArticleListPage
