import { View, Text, Image, ScrollView, Button, Swiper, SwiperItem } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { getConfigs, getAnnouncements, getActivities } from '../../api'
import ParticleBackground from '../../components/ParticleBackground'
import './index.scss'

export default function Index() {
  const [products, setProducts] = useState<any[]>([])
  const [announcements, setAnnouncements] = useState<any[]>([])
  const [activities, setActivities] = useState<any[]>([])
  const [typedText, setTypedText] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const fullText = "未来已来 AI 核心驱动"

  useLoad(() => {
    fetchData()
  })

  useEffect(() => {
    let i = 0
    const interval = setInterval(() => {
      i++
      setTypedText(fullText.slice(0, i))
      if (i >= fullText.length) clearInterval(interval)
    }, 150)
    return () => clearInterval(interval)
  }, [])

  const fetchData = async () => {
    setLoading(true)
    setError('')
    try {
      // Parallel fetch for better performance
      const [productsRes, announcementsRes, activitiesRes] = await Promise.all([
        getConfigs().catch(() => ({ results: [] })),
        getAnnouncements().catch(() => ({ results: [] })),
        getActivities().catch(() => ({ results: [] }))
      ])

      const productList = Array.isArray(productsRes) ? productsRes : (productsRes?.results || productsRes?.data || [])
      setProducts(productList)

      const announcementList = Array.isArray(announcementsRes) ? announcementsRes : (announcementsRes?.results || announcementsRes?.data || [])
      // Mock data for demo if empty
      if (announcementList.length === 0) {
        announcementList.push(
          { id: 101, title: 'Quant Speed AI 开发者大会即将开启报名' },
          { id: 102, title: '新品发布：AI小智 V2 性能提升300%' },
          { id: 103, title: '社区活动：分享你的边缘计算项目赢大奖' }
        )
      }
      setAnnouncements(announcementList)

      const activityList = Array.isArray(activitiesRes) ? activitiesRes : (activitiesRes?.results || activitiesRes?.data || [])
      // Mock data for demo if empty
      if (activityList.length === 0) {
        activityList.push({
          id: 201,
          title: '2025 AI 硬件黑客马拉松',
          start_time: '2025-05-20T10:00:00',
          cover_image: 'https://images.unsplash.com/photo-1550751827-4bd374c3f58b?q=80&w=2070&auto=format&fit=crop'
        }, {
          id: 202,
          title: '边缘计算实战训练营',
          start_time: '2025-06-15T09:00:00',
          cover_image: 'https://images.unsplash.com/photo-1518770660439-4636190af475?q=80&w=2070&auto=format&fit=crop'
        })
      }
      setActivities(activityList)

    } catch (err: any) {
      console.error(err)
      setError(err.errMsg || '加载失败，请检查网络')
    } finally {
      setLoading(false)
    }
  }

  const goToDetail = (id: number) => {
    Taro.navigateTo({ url: `/pages/goods/detail?id=${id}` })
  }

  const goToAnnouncement = (id: number) => {
    // Assuming generic topic detail or specific announcement page
    Taro.navigateTo({ url: `/subpackages/forum/detail/detail?id=${id}` })
  }

  const goToActivity = (id: number) => {
    Taro.navigateTo({ url: `/subpackages/forum/activity/detail?id=${id}` })
  }

  const goToActivityList = () => {
    Taro.navigateTo({ url: `/subpackages/forum/activity/index` })
  }

  return (
    <View className='page-container'>
      <ParticleBackground />
      
      <ScrollView scrollY className='content-scroll'>
        <View className='scroll-inner'>
        <View className='header'>
          <View className='logo-box'>
            <Image src='../../assets/logo.svg' className='logo-img' mode='widthFix' />
            <Text className='logo-text'>QUANT SPEED</Text>
          </View>
          
          <View className='title-container'>
            <Text className='title-text'>{typedText}</Text>
            <Text className='cursor'>|</Text>
          </View>
          <Text className='subtitle'>量迹 AI 硬件为您提供最强大的边缘计算能力</Text>
        </View>

        {/* News Ticker */}
        {!loading && announcements.length > 0 && (
          <View className='news-section fade-in-up'>
            <View className='news-inner'>
              <View className='news-icon-box'>
                <Text className='news-icon'>⚡</Text>
              </View>
              <Swiper
                className='news-swiper'
                vertical
                circular
                autoplay
                interval={4000}
                duration={600}
              >
                {announcements.map(item => (
                  <SwiperItem key={item.id} onClick={() => goToAnnouncement(item.id)}>
                    <View className='news-item'>
                      <Text className='news-tag'>NEWS</Text>
                      <Text className='news-title'>{item.title}</Text>
                    </View>
                  </SwiperItem>
                ))}
              </Swiper>
            </View>
          </View>
        )}

        {/* Activity Banner */}
        {!loading && activities.length > 0 && (
          <View className='activity-section fade-in-up' style={{ animationDelay: '0.1s' }}>
             <View className='section-header'>
                <Text className='section-title'>近期活动 / EVENTS</Text>
                <View className='more-btn' onClick={goToActivityList}>
                  <Text>MORE</Text>
                  <Text className='arrow'>→</Text>
                </View>
             </View>
             <Swiper
                className='activity-swiper'
                circular
                autoplay
                interval={5000}
                duration={600}
                previousMargin='30px'
                nextMargin='30px'
             >
                {activities.map(item => (
                  <SwiperItem key={item.id} className='activity-swiper-item' onClick={() => goToActivity(item.id)}>
                    <View className='activity-card'>
                      <Image 
                        src={item.display_banner_url || item.banner_url || item.cover_image || 'https://via.placeholder.com/600x300'} 
                        mode='aspectFill' 
                        className='activity-img' 
                      />
                      <View className='activity-overlay'>
                        <View className='activity-info'>
                          <Text className='activity-status'>报名中</Text>
                          <Text className='activity-title'>{item.title}</Text>
                          <Text className='activity-time'>{item.start_time ? item.start_time.split('T')[0] : 'TBD'}</Text>
                        </View>
                      </View>
                    </View>
                  </SwiperItem>
                ))}
             </Swiper>
          </View>
        )}

        {loading ? (
          <View className='skeleton-wrapper'>
            {[1, 2, 3].map(i => (
              <View key={i} className='skeleton-card' />
            ))}
          </View>
        ) : error ? (
          <View className='status-box'>
            <Text className='error-text'>{error}</Text>
            <Button className='btn-retry' onClick={fetchData}>重试</Button>
          </View>
        ) : (
          <View className='product-grid'>
            {products.map((item, index) => (
              <View 
                key={item.id} 
                className='card fade-in-up' 
                style={{ animationDelay: `${0.2 + index * 0.1}s` }}
                onClick={() => goToDetail(item.id)}
              >
                <View className='card-cover'>
                  {item.static_image_url ? (
                    <Image src={item.static_image_url} mode='aspectFill' className='card-img' />
                  ) : (
                    <View className='placeholder-img'>
                       <View className='radar-scan'></View>
                    </View>
                  )}
                  <View className='card-overlay' />
                </View>
                
                <View className='card-body'>
                  <View className='card-header'>
                    <Text className='card-title'>{item.name}</Text>
                    <Text className='price'>¥{item.price}</Text>
                  </View>
                  
                  <Text className='card-desc'>{item.description}</Text>
                  
                  <View className='tags'>
                    <View className='tag cyan'><Text>{item.chip_type}</Text></View>
                    {item.has_camera && <View className='tag blue'><Text>Camera</Text></View>}
                    {item.has_microphone && <View className='tag purple'><Text>Mic</Text></View>}
                  </View>
                  
                  <View className='card-footer'>
                     <Button className='btn-buy'>立即购买</Button>
                  </View>
                </View>
              </View>
            ))}
          </View>
        )}
        
        <View className='footer-spacer' />
        </View>
      </ScrollView>
    </View>
  )
}
