import React, { useState, useEffect } from 'react'
import Taro, { usePullDownRefresh, useRouter, useDidShow } from '@tarojs/taro'
import { View, Text, Image, Button } from '@tarojs/components'
import { getActivities, getMySignups } from '../../../api'
import './index.scss'

const ActivityList = () => {
  const router = useRouter()
  const [activities, setActivities] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [tab, setTab] = useState<'all' | 'mine'>('all')
  const [mySignups, setMySignups] = useState<any[]>([])

  useEffect(() => {
    if (router.params.tab === 'mine') {
        setTab('mine')
    }
  }, [router.params.tab])

  const fetchData = async () => {
    setLoading(true)
    try {
      if (tab === 'all') {
        const res = await getActivities()
        setActivities(res.results || res.data || (Array.isArray(res) ? res : []))
      } else {
        const res = await getMySignups()
        setMySignups(res.results || res.data || (Array.isArray(res) ? res : []))
      }
    } catch (error) {
      console.error(error)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
      Taro.stopPullDownRefresh()
    }
  }

  useEffect(() => {
    fetchData()
  }, [tab])

  useDidShow(() => {
    fetchData()
  })

  usePullDownRefresh(() => {
    fetchData()
  })

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

  const getStatusText = (status) => {
    const map = {
      'upcoming': '即将开始',
      'open': '报名中',
      'ongoing': '进行中',
      'ended': '已结束'
    }
    return map[status] || status
  }

  const renderList = (list) => {
    if (list.length === 0 && !loading) return <View className='empty'>暂无活动</View>

    return list.map(item => {
        // Handle API structure differences
        // For 'mine' tab, item is the signup record. activity_info is the full activity object.
        let activity = tab === 'mine' ? (item.activity_info || item.activity || item) : item
        
        // Safety check if activity is just an ID (number)
        if (typeof activity === 'number' || typeof activity === 'string') {
             // In this case we can't render the card properly without the activity details
             // Skip or render placeholder? Ideally we should have the object.
             // If we just have ID, we can't show title/image etc.
             // Let's create a placeholder object to avoid crash, but it won't show much info.
             activity = { id: activity, title: '加载中...', start_time: new Date().toISOString() }
        }

        if (!activity || !activity.id) return null
        
        return (
          <View key={activity.id} className='activity-card' onClick={() => goDetail(activity.id)}>
            <View className='card-cover-wrapper'>
                <Image 
                    src={activity.display_banner_url || activity.banner_url || activity.cover_image || 'https://via.placeholder.com/350x150'} 
                    mode='aspectFill' 
                    className='cover' 
                />
                <View className='status-tag'>
                    {getStatusText(activity.status)}
                </View>
            </View>
            
            <View className='info'>
              <View className='header'>
                <Text className='title'>{activity.title}</Text>
              </View>
              <View className='meta'>
                <View className='meta-item'>
                    <Text className='icon'>📅</Text>
                    <Text>{new Date(activity.start_time).toLocaleDateString()}</Text>
                </View>
                <View className='meta-item'>
                    <Text className='icon'>📍</Text>
                    <Text>{activity.location || '线上活动'}</Text>
                </View>
              </View>
              
              <View className='card-footer'>
                 <View className='participants'>
                    <Text className='highlight'>{activity.current_signups || 0}</Text>
                    <Text className='total'>/{activity.max_participants > 0 ? activity.max_participants : '∞'} 已报名</Text>
                 </View>
                 <Button className='btn-view'>查看详情</Button>
              </View>
            </View>
          </View>
        )
    })
  }

  return (
    <View className='activity-page'>
      <View className='tabs-header'>
        <View className='tabs-bg'>
            <View className={`tab ${tab === 'all' ? 'active' : ''}`} onClick={() => setTab('all')}>精彩活动</View>
            <View className={`tab ${tab === 'mine' ? 'active' : ''}`} onClick={() => setTab('mine')}>我的报名</View>
        </View>
      </View>

      <View className='list-container'>
        {renderList(tab === 'all' ? activities : mySignups)}
      </View>
    </View>
  )
}

export default ActivityList
