<template>
  <div class="admin-dashboard-page">
    <van-nav-bar
      title="管理后台"
      left-arrow
      @click-left="onClickLeft"
      right-text="新建"
      @click-right="onCreate"
      fixed
      placeholder
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多活动了"
        @load="onLoad"
      >
        <div class="activity-list">
          <div v-for="item in list" :key="item.id" class="activity-card" @click="onEdit(item)">
            <div class="card-cover">
              <van-image
                fit="cover"
                :src="item.coverImage || getRandomCover(item.id)"
                class="cover-image"
              >
                <template #error>
                  <div class="image-placeholder">
                    <van-icon name="photo-o" size="30" />
                  </div>
                </template>
              </van-image>
              <div class="status-tag">
                <van-tag :type="getStatusType(item.status)" round size="medium">
                  {{ formatStatus(item.status) }}
                </van-tag>
              </div>
            </div>

            <div class="card-content">
              <h3 class="activity-title van-ellipsis">{{ item.title }}</h3>

              <div class="info-row">
                <van-icon name="clock-o" class="icon" />
                <span class="text">{{ formatTimeRange(item.startTime, item.endTime) }}</span>
              </div>

              <div class="info-row">
                <van-icon name="location-o" class="icon" />
                <span class="text van-ellipsis">{{ item.location }}</span>
              </div>

              <div class="card-footer">
                <van-tag plain type="primary" size="medium">{{ item.category || '未分类' }}</van-tag>
                <div class="participants">
                  <van-icon name="friends-o" />
                  <span>{{ item.currentParticipants }}/{{ item.maxParticipants }} 已报名</span>
                </div>
              </div>

              <div class="card-actions">
                <van-button size="small" icon="edit" @click.stop="onEdit(item)">编辑</van-button>
                <van-button size="small" icon="qr" @click.stop="onCheckin(item)">签到</van-button>
                <van-button size="small" icon="chart-trending-o" @click.stop="onStats(item)">统计</van-button>
                <van-button size="small" icon="chat-o" @click.stop="onReviews(item)">评价</van-button>
                <van-button size="small" icon="delete-o" type="danger" @click.stop="onDelete(item)">删除</van-button>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { getActivities, deleteActivity } from '@/services/activity';
import type { Activity } from '@/types/activity';
import { showDialog, showToast } from 'vant';
import dayjs from 'dayjs';

const router = useRouter();

const list = ref<Activity[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
  }

  try {
    const res = await getActivities({
      current: currentPage.value,
      size: 10
    });
    
    const records = res.records || [];
    const total = res.total || 0;
    
    list.value.push(...records);
    loading.value = false;
    currentPage.value++;

    if (list.value.length >= total) {
      finished.value = true;
    }
  } catch (error) {
    loading.value = false;
    finished.value = true;
  }
};

const onRefresh = () => {
  refreshing.value = true;
  finished.value = false;
  loading.value = true;
  currentPage.value = 1;
  list.value = [];
  onLoad();
};

const onClickLeft = () => {
  router.push('/user');
};

const onCreate = () => {
  router.push('/admin/activity/new');
};

const onEdit = (item: Activity) => {
  router.push(`/admin/activity/edit/${item.id}`);
};

const onCheckin = (item: Activity) => {
  router.push(`/admin/activity/checkin/${item.id}`);
};

const onStats = (item: Activity) => {
  router.push(`/admin/activity/stats/${item.id}`);
};

const onReviews = (item: Activity) => {
  router.push(`/admin/activity/reviews/${item.id}`);
};

const onDelete = (item: Activity) => {
  showDialog({
    title: '删除活动',
    message: `确定要删除 "${item.title}" 吗？`,
    showCancelButton: true
  }).then(async () => {
    try {
      await deleteActivity(item.id);
      showToast('已删除');
      onRefresh();
    } catch (error) {
      // Error handled
    }
  });
};

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

const getStatusType = (status: number) => {
    if (status === 1) return 'success';
    if (status === 2) return 'primary';
    if (status === 3) return 'default';
    return 'warning';
};

const formatTimeRange = (start: string, end: string) => {
  const s = dayjs(start);
  const e = dayjs(end);
  if (s.isSame(e, 'day')) {
    return `${s.format('MM-DD HH:mm')} - ${e.format('HH:mm')}`;
  }
  return `${s.format('MM-DD HH:mm')} - ${e.format('MM-DD HH:mm')}`;
};

const getRandomCover = (id: number) => {
  return `https://picsum.photos/seed/${id}/600/400`;
};
</script>

<style scoped lang="scss">
.admin-dashboard-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

.activity-list {
  padding: 12px;
}

.activity-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: all 0.2s;

  &:active {
    transform: scale(0.99);
  }

  .card-cover {
    position: relative;
    height: 160px;
    width: 100%;

    .cover-image {
      width: 100%;
      height: 100%;
    }

    .status-tag {
      position: absolute;
      top: 12px;
      right: 12px;
      z-index: 1;
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f5f5;
      color: #dcdee0;
    }
  }

  .card-content {
    padding: 12px 16px;

    .activity-title {
      margin: 0 0 10px;
      font-size: 17px;
      font-weight: 600;
      color: #323233;
      line-height: 1.4;
    }

    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      color: #646566;
      font-size: 14px;

      .icon {
        margin-right: 8px;
        font-size: 16px;
        color: #969799;
      }

      .text {
        flex: 1;
      }
    }

    .card-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f5f6f7;

      .participants {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #969799;

        .van-icon {
          margin-right: 4px;
          font-size: 15px;
        }
      }
    }

    .card-actions {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f5f6f7;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
}
</style>
