<template>
  <div class="my-registrations-page">
    <van-nav-bar
      title="我的报名"
      fixed
      placeholder
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多记录了"
        @load="onLoad"
      >
        <div v-for="item in list" :key="item.id" class="ticket-card">
          <div class="ticket-header">
            <h3>{{ item.activityTitle }}</h3>
            <!-- Status: 0=Cancelled, 1=Valid, 2=Checked In -->
            <van-tag :type="getStatusType(item)">
              {{ getStatusText(item) }}
            </van-tag>
          </div>
          <div class="ticket-body">
            <p><strong>开始:</strong> {{ formatTime(item.activityStartTime) }}</p>
            <p><strong>结束:</strong> {{ formatTime(item.activityEndTime) }}</p>
            <p><strong>地点:</strong> {{ item.activityLocation }}</p>
            <p><strong>票码:</strong> {{ item.ticketCode }}</p>
          </div>
          <div class="ticket-footer">
            <van-button
                 v-if="isEnded(item.activityEndTime) || item.status === 2"
                 size="small"
                 type="warning"
                 plain
                 @click="handleReview(item)"
            >
              去评价
            </van-button>
            <van-button
              v-if="item.status === 1 && !isEnded(item.activityEndTime)"
              size="small"
              type="success"
              plain
              @click="handleDownloadTicket(item)"
            >
              下载电子票
            </van-button>
            <van-button v-if="item.status === 1 && !isEnded(item.activityEndTime)" size="small" type="primary" plain @click="showQrCode(item)">入场码</van-button>
            <van-button v-if="item.status === 1 && !isEnded(item.activityEndTime)" size="small" type="danger" plain @click="handleCancel(item)">取消报名</van-button>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- Floating Scan Button -->
    <div class="floating-scan-btn" @click="showScanner = true">
      <van-icon name="scan" size="32" color="#fff" />
    </div>

    <!-- QR Scanner Overlay -->
    <van-popup v-model:show="showScanner" position="bottom" :style="{ height: '100%' }">
       <WebQRScanner 
         v-if="showScanner" 
         @result="handleScanResult" 
         @close="showScanner = false" 
       />
    </van-popup>

    <!-- QR Code Dialog -->
    <van-dialog v-model:show="qrVisible" title="入场二维码" :show-confirm-button="false" close-on-click-overlay>
      <div style="text-align: center; padding: 20px;">
        <van-image
          width="200"
          height="200"
          :src="currentQrUrl"
        />
        <p>{{ currentTicketCode }}</p>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { getMyRegistrations, cancelRegistration, downloadTicket } from '@/services/registration';
import { scanCheckinQr } from '@/services/checkin';
import type { Registration } from '@/types/registration';
import { showToast, showDialog } from 'vant';
import dayjs from 'dayjs';
import WebQRScanner from '@/components/WebQRScanner.vue';

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

const qrVisible = ref(false);
const currentQrUrl = ref('');
const currentTicketCode = ref('');

const showScanner = ref(false);

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

  try {
    const res = await getMyRegistrations({
      current: currentPage.value,
      size: 10
    });
    
    // Check if res is array (if backend returns array directly) or paginated object
    // Based on API docs: { code: 200, data: { records: [] } }
    // Request interceptor returns res.data which is 'data' object.
    const records = res.records || [];
    const total = res.total || 0;
    
    if (currentPage.value === 1) {
      list.value = [];
    }

    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 = () => {
  finished.value = false;
  loading.value = true;
  currentPage.value = 1;
  onLoad();
};

onActivated(() => {
  onRefresh();
});

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

const isEnded = (endTime: string) => {
  if (!endTime) return false;
  return dayjs().isAfter(dayjs(endTime));
};

const showQrCode = (item: Registration) => {
  // Use a QR code generator API or just display code for now if no image
  // 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + item.ticketCode
  currentQrUrl.value = item.ticketPdfUrl || `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${item.ticketCode}`;
  currentTicketCode.value = item.ticketCode;
  qrVisible.value = true;
};

const handleCancel = (item: Registration) => {
  showDialog({
    title: '取消报名',
    message: '确定要取消这次报名吗？',
    showCancelButton: true
  }).then(async () => {
    try {
      await cancelRegistration(item.id);
      showToast('取消成功');
      onRefresh();
    } catch (error) {
      // Error handled
    }
  });
};

const handleReview = (item: Registration) => {
  // Navigate to write review page or list?
  // Requirement says "enter review page"
  // We can use the ActivityDetail or a dedicated review page.
  // Assuming ActivityDetail has review function or we add one.
  // Actually we have `submitReview` in `activity` or `review` services.
  // Let's navigate to `/activity/:id` and hash #review or new route `/review/new/:activityId`
  // But strictly `ActivityDetail` has review ability? No, we didn't implement UI for review submission in detail yet.
  // Wait, I will need to check if I have a review submission page.
  // I created `MyReviews.vue` (list) and `ActivityReviews.vue` (admin list).
  // I need a place to submit review. Pop up a dialog here? Or navigate to Activity Detail and scroll to review?
  // Let's create a simple review submission dialog HERE or navigate to Activity Detail.
  // For now, navigate to ActivityDetail, assuming user can review there.
  // Or better, navigate to ActivityDetail.
  router.push(`/activity/${item.activityId}`);
};

const handleDownloadTicket = async (item: Registration) => {
  try {
    showToast({ type: 'loading', message: '下载中...', duration: 0 });

    const blob = await downloadTicket(item.id);

    // 创建 Blob URL
    const url = window.URL.createObjectURL(blob);

    // 创建下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = `ticket_${item.ticketCode}.pdf`;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    showToast({ type: 'success', message: '下载成功' });
  } catch (error) {
    showToast('下载失败，请稍后重试');
  }
};

const getStatusType = (item: Registration) => {
  // Check if activity has ended first
  if (isEnded(item.activityEndTime)) return 'warning';
  if (item.status === 1) return 'primary';
  if (item.status === 2) return 'success';
  return 'default';
};

const getStatusText = (item: Registration) => {
  // Check if activity has ended first
  if (isEnded(item.activityEndTime)) return '已结束';
  if (item.status === 1) return '已报名';
  if (item.status === 2) return '已签到';
  return '已取消';
};

const handleScanResult = async (decodedText: string) => {
  // Stop scanning immediately to prevent multiple scans
  // showScanner.value = false; // Wait, user wants to see success msg? Or just close?
  // "Increase scanning success after auto close" -> Close AFTER success.
  
  try {
     showToast({ type: 'loading', message: '签到中...', duration: 0 });
     await scanCheckinQr(decodedText);
     showToast({ type: 'success', message: '签到成功' });
     
     // Close scanner after short delay to let user see success
     setTimeout(() => {
       showScanner.value = false;
       onRefresh();
     }, 1000);
     
  } catch (error) {
     showToast('签到失败/无效二维码');
     // Keep scanner open to try again? 
     // Or close? User said "auto close", usually implies success case.
  }
};
</script>

<style scoped lang="scss">
.my-registrations-page {
  min-height: 100vh;
  background-color: #f7f8fa;

  .ticket-card {
    background: #fff;
    margin: 16px;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);

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

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

    .ticket-body {
      color: #666;
      font-size: 14px;
      p {
        margin: 4px 0;
      }
    }

    .ticket-footer {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #eee;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }
  .floating-scan-btn {
    position: fixed;
    right: 24px;
    bottom: 80px;
    width: 60px;
    height: 60px;
    background-color: var(--van-primary-color);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    z-index: 1000;
    cursor: pointer;
    
    &:active {
      transform: scale(0.95);
    }
  }
}
</style>
