<template>
  <div class="activity-detail-page" v-if="activity">
    <van-nav-bar
      title="活动详情"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
    />
    
    <van-image
      width="100%"
      height="200"
      fit="cover"
      :src="activity.coverImage || 'https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg'"
    />
    
    <div class="content">
      <h1 class="title">{{ activity.title }}</h1>
      <div class="meta">
        <van-tag type="primary">{{ activity.category }}</van-tag>
        <van-tag type="success" style="margin-left: 8px">{{ formatStatus(activity.status) }}</van-tag>
      </div>
      
      <van-cell-group inset class="info-group">
        <van-cell icon="clock-o" title="时间" :label="`${formatTime(activity.startTime)} - ${formatTime(activity.endTime)}`" />
        <van-cell icon="location-o" title="地点" :label="activity.location" />
        <van-cell icon="friends-o" title="人数" :label="`${activity.currentParticipants} / ${activity.maxParticipants}`" />
        <van-cell icon="manager-o" title="主办方" :label="activity.adminName || '管理员'" />
      </van-cell-group>
      
      <div class="description">
        <h3>活动简介</h3>
        <p>{{ activity.description || '暂无简介' }}</p>
      </div>

      <!-- Reviews Section -->
      <div class="reviews-section">
        <div class="reviews-header">
          <h3>活动评价</h3>
          <div class="rating-summary" v-if="activity.reviewCount && activity.reviewCount > 0">
            <van-rate :model-value="activity.averageRating" readonly size="16px" color="#ffd21e" />
            <span class="rating-text">{{ activity.averageRating?.toFixed(1) }} ({{ activity.reviewCount }}条评价)</span>
          </div>
        </div>

        <van-pull-refresh v-model="reviewsRefreshing" @refresh="onReviewsRefresh">
          <van-list
            v-model:loading="reviewsLoading"
            :finished="reviewsFinished"
            finished-text="没有更多评价了"
            @load="onLoadReviews"
          >
            <div v-if="reviews.length === 0 && !reviewsLoading" class="empty-reviews">
              <van-empty description="暂无评价" />
            </div>
            <div v-for="review in reviews" :key="review.id" class="review-card">
              <div class="review-header">
                <div class="user-info">
                  <van-image 
                    round 
                    width="32" 
                    height="32" 
                    :src="review.userAvatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" 
                  />
                  <span class="username">{{ review.userName }}</span>
                </div>
                <span class="time">{{ formatReviewTime(review.createdAt) }}</span>
              </div>
              <van-rate :model-value="review.rating" readonly size="14px" color="#ffd21e" />
              <p class="review-content" v-if="review.content">{{ review.content }}</p>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <van-action-bar>
      <van-action-bar-icon icon="chat-o" :text="`评价(${activity.reviewCount || 0})`" @click="scrollToReviews" />
      <van-action-bar-button type="danger" text="立即报名" @click="handleRegister" v-if="!activity.isRegistered && activity.status === 1" />
      <van-action-bar-button type="success" text="已报名" disabled v-if="activity.isRegistered" />
      <van-action-bar-button type="primary" text="写评价" @click="showReviewDialog" v-if="canReview" />
      <van-action-bar-button type="warning" text="已结束" disabled v-if="activity.status > 2 && !canReview" />
    </van-action-bar>

    <!-- Review Submit Dialog -->
    <ReviewSubmitDialog 
      v-model:show="reviewDialogVisible" 
      :activity-id="id" 
      @success="handleReviewSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { getActivityDetail } from '@/services/activity';
import { getActivityReviews } from '@/services/review';
import type { Activity } from '@/types/activity';
import type { Review } from '@/types/review';
import { showToast } from 'vant';
import dayjs from 'dayjs';
import ReviewSubmitDialog from '@/components/ReviewSubmitDialog.vue';

const route = useRoute();
const activity = ref<Activity | null>(null);
const reviews = ref<Review[]>([]);
const reviewsLoading = ref(false);
const reviewsFinished = ref(false);
const reviewsRefreshing = ref(false);
const reviewsCurrentPage = ref(1);
const reviewDialogVisible = ref(false);

const id = Number(route.params.id);

const canReview = computed(() => {
  if (!activity.value) return false;
  // User can review if they registered and activity has ended
  return activity.value.isRegistered && activity.value.status === 3;
});

onMounted(async () => {
  try {
    const res = await getActivityDetail(id);
    activity.value = res;
  } catch (error) {
    showToast('加载失败');
  }
});

const onClickLeft = () => history.back();

import { registerActivity } from '@/services/registration';

const handleRegister = async () => {
  if (!activity.value) return;
  
  try {
    await registerActivity(activity.value.id);
    showToast('报名成功！可在“我的票券”中查看');
    // Refresh activity data to update status
    const updated = await getActivityDetail(id);
    activity.value = updated;
  } catch (error) {
    // Error handled by interceptor
  }
};

const onLoadReviews = async () => {
  if (reviewsRefreshing.value) {
    reviews.value = [];
    reviewsRefreshing.value = false;
  }

  try {
    const res = await getActivityReviews(id, {
      current: reviewsCurrentPage.value,
      size: 10
    });
    
    const records = res.records || [];
    const total = res.total || 0;
    
    reviews.value.push(...records);
    reviewsLoading.value = false;
    reviewsCurrentPage.value++;

    if (reviews.value.length >= total) {
      reviewsFinished.value = true;
    }
  } catch (error) {
    reviewsLoading.value = false;
    reviewsFinished.value = true;
  }
};

const onReviewsRefresh = () => {
  reviewsFinished.value = false;
  reviewsLoading.value = true;
  reviewsCurrentPage.value = 1;
  onLoadReviews();
};

const scrollToReviews = () => {
  const reviewsSection = document.querySelector('.reviews-section');
  if (reviewsSection) {
    reviewsSection.scrollIntoView({ behavior: 'smooth' });
  }
};

const showReviewDialog = () => {
  reviewDialogVisible.value = true;
};

const handleReviewSuccess = async () => {
  // Refresh reviews and activity data
  onReviewsRefresh();
  try {
    const updated = await getActivityDetail(id);
    activity.value = updated;
  } catch (error) {
    // Error handled
  }
};

const formatReviewTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD');
};

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

const formatStatus = (status: number) => {
  const map: Record<number, string> = {
    0: '草稿',
    1: '报名中',
    2: '进行中',
    3: '已结束',
    4: '已取消',
  };
  return map[status] || '未知';
};
</script>

<style scoped lang="scss">
.activity-detail-page {
  padding-bottom: 50px;
  background-color: #f7f8fa;
  min-height: 100vh;

  .content {
    padding: 16px;
    
    .title {
      font-size: 24px;
      margin: 0 0 10px;
      background: #fff;
      padding: 16px;
      border-radius: 8px;
    }
    
    .meta {
      margin-bottom: 16px;
      padding: 0 16px;
    }
    
    .info-group {
      margin-bottom: 16px;
    }
    
    .description {
      background: #fff;
      padding: 16px;
      border-radius: 8px;
      
      h3 {
        margin: 0 0 10px;
        font-size: 16px;
      }
      
      p {
        color: #666;
        line-height: 1.6;
        margin: 0;
      }
    }

    .reviews-section {
      background: #fff;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 16px;

      .reviews-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #eee;

        h3 {
          margin: 0;
          font-size: 16px;
        }

        .rating-summary {
          display: flex;
          align-items: center;
          gap: 8px;

          .rating-text {
            font-size: 14px;
            color: #666;
          }
        }
      }

      .empty-reviews {
        padding: 20px 0;
      }

      .review-card {
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .review-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .user-info {
            display: flex;
            align-items: center;
            gap: 8px;

            .username {
              font-size: 14px;
              color: #333;
              font-weight: 500;
            }
          }

          .time {
            font-size: 12px;
            color: #999;
          }
        }

        .review-content {
          margin: 8px 0 0;
          font-size: 14px;
          color: #666;
          line-height: 1.5;
        }
      }
    }
  }
}
</style>
