<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <view class="sticky top-0 z-10 bg-white shadow-sm">
      <view class="flex items-center justify-between px-4 py-3">
        <view class="flex items-center space-x-2">
          <text class="iconfont icon-arrow-left text-xl" @tap="goBack"></text>
          <text class="text-2xl font-bold">相亲活动</text>
        </view>
        <view class="flex items-center space-x-4">
          <text class="iconfont icon-search text-xl"></text>
          <text class="iconfont icon-filter text-xl"></text>
        </view>
      </view>
      <!-- 筛选器 -->
      <view class="flex px-4 pb-3 space-x-4">
        <view
          :class="[
            'px-4 py-2 rounded-full text-sm transition-all duration-300',
            currentFilter === '1' ? 'bg-primary/90 shadow-lg shadow-primary/20' : 'bg-gray-100',
          ]"
          @tap="changeFilter('1')"
        >
          <text :class="currentFilter === '1' ? 'text-gray-600' : 'text-gray-600'">全部</text>
        </view>
        <view
          :class="[
            'px-4 py-2 rounded-full text-sm transition-all duration-300',
            currentFilter === '2' ? 'bg-primary/90 shadow-lg shadow-primary/20' : 'bg-gray-100',
          ]"
          @tap="changeFilter('2')"
        >
          <text :class="currentFilter === '2' ? 'text-gray-600' : 'text-gray-600'">报名中</text>
        </view>
        <view
          :class="[
            'px-4 py-2 rounded-full text-sm transition-all duration-300',
            currentFilter === '3' ? 'bg-primary/90 shadow-lg shadow-primary/20' : 'bg-gray-100',
          ]"
          @tap="changeFilter('3')"
        >
          <text :class="currentFilter === '3' ? 'text-gray-600' : 'text-gray-600'">已结束</text>
        </view>
      </view>
    </view>

    <!-- 活动列表 -->
    <view class="px-4 pt-2 pb-8 overflow-hidden">
      <scroll-view
        class="space-y-4"
        scroll-y
        @scrolltolower="loadMore"
        refresher-enabled
        :refresher-triggered="loading"
        @refresherrefresh="onRefresh"
      >
        <!-- 加载状态 -->
        <view v-if="loading" class="flex justify-center items-center py-8">
          <text class="text-gray-500">加载中...</text>
        </view>

        <!-- 错误状态 -->
        <view v-else-if="error" class="flex justify-center items-center py-8">
          <text class="text-red-500">{{ error }}</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="!activities.length" class="flex justify-center items-center py-8">
          <text class="text-gray-500">暂无活动</text>
        </view>

        <view v-else class="space-y-4">
          <view
            class="bg-white rounded-2xl shadow-lg overflow-hidden transform transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]"
            v-for="item in activities"
            :key="item.id"
            @tap="viewActivity(item)"
          >
            <view class="relative">
              <image :src="item.eventAvatar" mode="aspectFill" class="w-full h-40 object-cover" />
              <view
                class="absolute top-3 right-3 px-3 py-1 bg-white/90 rounded-full backdrop-blur-sm"
              >
                <text class="text-sm text-primary font-medium">¥{{ item.eventPrice }}</text>
              </view>
              <view
                :class="[
                  'absolute top-3 left-3 px-3 py-1 rounded-full text-sm font-medium',
                  isOngoing(item) ? 'bg-green-500/90 text-white' : 'bg-gray-500/90 text-white',
                ]"
              >
                {{ isOngoing(item) ? '报名中' : '已结束' }}
              </view>
            </view>
            <view class="p-4">
              <text class="block text-lg font-bold mb-2">{{ item.eventTitle }}</text>
              <view class="flex items-center text-sm text-gray-500">
                <text class="iconfont icon-time mr-1"></text>
                <text>截止时间: {{ formatDate(item.endTime) }}</text>
              </view>
              <view class="mt-3 flex items-center justify-between">
                <view class="flex items-center">
                  <view class="flex -space-x-2">
                    <image
                      v-for="(avatar, index) in getRandomAvatars(3)"
                      :key="index"
                      :src="avatar"
                      class="w-8 h-8 rounded-full border-2 border-white"
                    />
                  </view>
                  <text class="ml-2 text-sm text-gray-500">已有 {{ item.eventNumber }} 人报名</text>
                </view>
                <view
                  class="px-4 py-2 bg-primary text-white text-sm rounded-full"
                  @tap.stop="handleJoin(item)"
                >
                  立即报名
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载完成提示 -->
        <view
          v-if="!loading && activities.length > 0 && activities.length >= total"
          class="py-4 text-center text-gray-500"
        >
          <text>没有更多数据了</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { joinEventAPI } from '@/service/event'
import type { EventItem } from '@/service/event/type'
import { formatDate } from '@/utils/date'

// 状态
const loading = ref(false)
const error = ref('')
const activities = ref<EventItem[]>([])
const currentFilter = ref<'1' | '2' | '3'>('1') // 1-全部 2-报名中 3-已结束
const total = ref(0)

// 获取活动列表
const fetchActivities = async (isRefresh = false) => {
  if (loading.value) return
  loading.value = true
  error.value = ''

  try {
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('获取活动列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 判断活动是否进行中
const isOngoing = (item: EventItem) => {
  const now = new Date().getTime()
  const endTime = new Date(item.endTime).getTime()
  return endTime > now
}

// 加载更多
const loadMore = () => {
  if (activities.value.length >= total.value) return
  fetchActivities()
}

// 下拉刷新
const onRefresh = () => {
  fetchActivities(true)
}

// 切换筛选
const changeFilter = (filter: '1' | '2' | '3') => {
  currentFilter.value = filter
  fetchActivities(true)
}

// 查看活动详情
const viewActivity = (item: EventItem) => {
  uni.navigateTo({
    url: `/pages/activity/detail?id=${item.id}`,
  })
}

// 处理报名
const handleJoin = async (item: EventItem) => {
  try {
    const res = await joinEventAPI(item.id)
    if (res.code === 200) {
      uni.showToast({
        title: '报名成功',
        icon: 'success',
      })
      // 刷新列表
      fetchActivities(true)
    } else {
      uni.showToast({
        title: res.message || '报名失败',
        icon: 'error',
      })
    }
  } catch (err) {
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'error',
    })
    console.error('报名失败:', err)
  }
}

const goBack = () => {
  uni.navigateBack()
}

// 获取随机头像（实际项目中应该使用真实数据）
const getRandomAvatars = (count: number) => {
  return Array(count).fill(
    'https://bpic.588ku.com/element_origin_min_pic/23/07/11/d32dabe266d10da8b21bd640a2e9b611.jpg',
  )
}

// 初始化
onMounted(() => {
  fetchActivities()
})
</script>
