<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useSocketClient } from '../composables/useSocketClient';
import { LotteryMachine, type Participant, type LotteryPhase } from '../pixi/LotteryMachine';
import type { AdminState } from '@gala/shared/types';
import { SOCKET_EVENTS } from '@gala/shared/constants';

const router = useRouter();
const { isConnected, onlineUsers, adminState, onAdminStateChange } = useSocketClient();

// Pixi canvas ref
const canvasRef = ref<HTMLCanvasElement | null>(null);
let lotteryMachine: LotteryMachine | null = null;

// Local state
const currentPhase = ref<LotteryPhase>('idle');
const currentPrize = ref({ level: '', name: '' });
const winners = ref<Participant[]>([]);
const currentRound = ref(1);
const isLoading = ref(true);
const participantCount = ref(0);

// Track previous lottery subPhase to detect changes
let previousSubPhase: string | null = null;

// Prize configuration - 从服务器加载
const prizes = ref<Array<{ level: string; name: string; winnerCount: number; poolTag?: string }>>([]);

// 从 API 获取奖项配置
async function fetchPrizes() {
  try {
    const response = await fetch('/api/admin/prizes');
    const data = await response.json();
    if (data.success && data.data?.prizes) {
      prizes.value = data.data.prizes;
      // 更新当前奖品显示
      const currentConfig = data.data.prizes.find((p: any) => p.round === currentRound.value);
      if (currentConfig) {
        currentPrize.value = { level: currentConfig.level, name: currentConfig.name };
      }
      console.log('[抽奖] 已加载奖项配置:', prizes.value);
    }
  } catch (error) {
    console.error('[抽奖] 获取奖项配置失败:', error);
  }
}

// 从服务器加载的参与者列表
let realParticipants: Participant[] = [];

// 从 API 获取导入的参与者名单
async function fetchParticipants() {
  try {
    isLoading.value = true;
    const response = await fetch('/api/admin/participants');
    const data = await response.json();
    
    if (data.success && data.data?.participants) {
      // 将后端格式转换为前端 Participant 格式
      realParticipants = data.data.participants.map((p: any) => ({
        id: p.id,
        name: p.name,
        department: p.position, // 岗位作为部门显示
        zodiac: p.tags?.includes('horse') ? 'horse' : 'other',
        age: new Date().getFullYear() - p.birthYear,
      }));
      participantCount.value = realParticipants.length;
      console.log(`[抽奖] 已加载 ${realParticipants.length} 名参与者`);
    } else {
      console.warn('[抽奖] 未找到参与者数据，请先导入名单');
    }
  } catch (error) {
    console.error('[抽奖] 获取参与者失败:', error);
  } finally {
    isLoading.value = false;
  }
}

// Unsubscribe function
let unsubscribeLottery: (() => void) | null = null;

function goBack() {
  router.push('/');
}

function handlePhaseChange(phase: LotteryPhase) {
  currentPhase.value = phase;
}

function handleWinnersRevealed(revealedWinners: Participant[]) {
  winners.value = revealedWinners;
}

// Handle admin state changes from control panel
function handleAdminStateChange(state: AdminState) {
  const lottery = state.lottery;
  const newSubPhase = lottery.subPhase;

  // Update local state
  currentRound.value = lottery.round;
  currentPrize.value = {
    level: lottery.prizeLevel,
    name: lottery.prizeName,
  };

  // Detect phase transitions and trigger actions
  if (newSubPhase !== previousSubPhase) {
    console.log(`[BigScreen] Lottery phase: ${previousSubPhase} -> ${newSubPhase}`);

    if (newSubPhase === 'GALAXY') {
      // Clear winners when starting new round
      winners.value = [];
      startGalaxy();
    } else if (newSubPhase === 'STORM') {
      startRolling();
    } else if (newSubPhase === 'REVEAL') {
      // Use winners from server instead of local random
      if (lottery.currentWinners && lottery.currentWinners.length > 0) {
        const serverWinners = lottery.currentWinners.map(w => ({
          id: w.id,
          name: w.name,
          department: w.department,
          zodiac: 'unknown' as const,
          age: 0,
        }));
        winners.value = serverWinners;
        stopAndRevealWithWinners(serverWinners);
      } else {
        stopAndReveal();
      }
    } else if (newSubPhase === 'IDLE' && previousSubPhase === 'COMPLETE') {
      resetLottery();
    }

    previousSubPhase = newSubPhase;
  }
}

// Control functions
function startGalaxy() {
  if (!lotteryMachine) return;

  // Clear previous winners
  winners.value = [];

  // 使用真实参与者数据（如果有的话）
  const participants = realParticipants.length > 0 ? realParticipants : [];
  
  if (participants.length === 0) {
    console.warn('[抽奖] 无参与者数据，请先导入名单');
    return;
  }

  // Set participants and start galaxy view
  lotteryMachine.setParticipants(participants);

  // Apply filter for Round 4 (Horse zodiac)
  if (currentRound.value === 4) {
    lotteryMachine.filterParticipants({ zodiac: 'horse' });
  }

  lotteryMachine.startGalaxy();
}

function startRolling() {
  if (!lotteryMachine) return;
  lotteryMachine.startStorm();
}

function stopAndReveal() {
  if (!lotteryMachine) return;

  // 使用真实参与者数据进行本地随机抽取（服务器未返回中奖者的降级方案）
  const participants = realParticipants.length > 0 ? realParticipants : [];
  const prize = prizes.value.find(p => p.round === currentRound.value) || prizes.value[0];
  const eligibleParticipants = participants.filter(p => {
    if (currentRound.value === 4) {
      return p.zodiac === 'horse';
    }
    return true;
  });

  const shuffled = [...eligibleParticipants].sort(() => Math.random() - 0.5);
  const winnerIds = shuffled.slice(0, prize?.winnerCount || 1).map(p => p.id);

  lotteryMachine.revealWinners(winnerIds);
}

// Reveal winners using server-provided data
function stopAndRevealWithWinners(serverWinners: Participant[]) {
  if (!lotteryMachine) return;

  // Map server winners to participant IDs for the lottery machine
  const winnerIds = serverWinners.map(w => w.id);

  // Add server winners to participants if not already present
  serverWinners.forEach(sw => {
    if (!realParticipants.find(p => p.id === sw.id)) {
      realParticipants.push(sw);
    }
  });

  lotteryMachine.revealWinners(winnerIds);
}

function nextRound() {
  if (!lotteryMachine) return;

  currentRound.value = Math.min(4, currentRound.value + 1);
  const nextPrize = prizes.value.find(p => p.round === currentRound.value);
  if (nextPrize) {
    currentPrize.value = { level: nextPrize.level, name: nextPrize.name };
  }
  winners.value = [];

  lotteryMachine.reset();
}

function resetLottery() {
  if (!lotteryMachine) return;

  currentRound.value = 1;
  const firstPrize = prizes.value.find(p => p.round === 1) || prizes.value[0];
  if (firstPrize) {
    currentPrize.value = { level: firstPrize.level, name: firstPrize.name };
  }
  winners.value = [];

  lotteryMachine.reset();
}

onMounted(async () => {
  await nextTick();

  // 首先从服务器加载配置和参与者数据
  await Promise.all([fetchPrizes(), fetchParticipants()]);

  // Initialize lottery machine
  if (canvasRef.value) {
    lotteryMachine = new LotteryMachine();
    await lotteryMachine.init(canvasRef.value);

    // Set callbacks
    lotteryMachine.onPhase(handlePhaseChange);
    lotteryMachine.onWinners(handleWinnersRevealed);
  }

  // Subscribe to admin state changes from control panel
  unsubscribeLottery = onAdminStateChange(handleAdminStateChange);

  // Request initial admin state
  const socket = useSocketClient().getSocket();
  if (socket) {
    socket.emit(SOCKET_EVENTS.ADMIN_STATE_SYNC as any);
  }
});

onUnmounted(() => {
  if (lotteryMachine) {
    lotteryMachine.destroy();
    lotteryMachine = null;
  }

  if (unsubscribeLottery) {
    unsubscribeLottery();
  }
});
</script>

<template>
  <div class="lucky-draw-view">
    <!-- Pixi Canvas (full screen) -->
    <canvas ref="canvasRef" class="lottery-canvas"></canvas>

    <!-- Overlay UI -->
    <div class="overlay-ui">
      <!-- Header -->
      <header class="header">
        <button class="back-btn" @click="goBack">← 返回</button>
        <div class="round-indicator">
          <span class="round-label">第 {{ currentRound }} 轮</span>
          <span v-if="currentRound === 4" class="filter-badge">🐴 马年限定</span>
        </div>
        <div class="status">
          <span class="online-count">{{ onlineUsers }} 人在线</span>
          <span class="connection-dot" :class="{ connected: isConnected }"></span>
        </div>
      </header>

      <!-- Prize Display -->
      <div class="prize-display" :class="{ hidden: currentPhase === 'storm' }">
        <div class="prize-badge">
          <span class="prize-level">{{ currentPrize.level }}</span>
          <span class="prize-name">{{ currentPrize.name }}</span>
        </div>
      </div>

      <!-- Phase Indicator -->
      <div class="phase-indicator">
        <span class="phase-text">
          {{ currentPhase === 'idle' ? '准备就绪' :
             currentPhase === 'galaxy' ? '参与者展示' :
             currentPhase === 'storm' ? '抽奖进行中...' :
             currentPhase === 'reveal' ? '揭晓中...' :
             '恭喜中奖！' }}
        </span>
      </div>

      <!-- Winners Display (shown after reveal) -->
      <div v-if="currentPhase === 'complete' && winners.length > 0" class="winners-overlay">
        <h2 class="winners-title gold-text">🎉 恭喜以下获奖者 🎉</h2>
        <div class="winners-list">
          <div v-for="winner in winners" :key="winner.id" class="winner-item">
            <span class="winner-name">{{ winner.name }}</span>
            <span class="winner-dept">{{ winner.department }}</span>
          </div>
        </div>
      </div>

      <!-- Status Panel (controlled by admin) -->
      <div class="status-panel">
        <span class="status-text">
          {{ currentPhase === 'idle' ? '等待管理员开始...' :
             currentPhase === 'galaxy' ? '参与者展示中' :
             currentPhase === 'storm' ? '抽奖进行中...' :
             currentPhase === 'reveal' ? '揭晓中...' :
             '本轮抽奖完成' }}
        </span>
        <span class="admin-hint">由管理控制台控制</span>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@use '../assets/styles/variables.scss' as *;

.lucky-draw-view {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.lottery-canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

.overlay-ui {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  pointer-events: none;

  > * {
    pointer-events: auto;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px 50px;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.5) 0%, transparent 100%);

  .back-btn {
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid $color-gold;
    color: $color-gold;
    padding: 10px 20px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    transition: all $transition-fast;
    backdrop-filter: blur(10px);

    &:hover {
      background: rgba($color-gold, 0.2);
    }
  }

  .round-indicator {
    display: flex;
    align-items: center;
    gap: 12px;

    .round-label {
      font-size: 24px;
      color: $color-gold;
      font-weight: bold;
    }

    .filter-badge {
      padding: 6px 12px;
      background: rgba($color-gold, 0.2);
      border: 1px solid $color-gold;
      border-radius: 20px;
      font-size: 14px;
      color: $color-gold;
    }
  }

  .status {
    display: flex;
    align-items: center;
    gap: 12px;

    .online-count {
      color: $color-text-muted;
      font-size: 18px;
    }

    .connection-dot {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: #666;
      transition: background 0.3s;

      &.connected {
        background: #4ade80;
        box-shadow: 0 0 10px rgba(74, 222, 128, 0.5);
      }
    }
  }
}

.prize-display {
  display: flex;
  justify-content: center;
  padding: 20px;
  transition: opacity 0.5s, transform 0.5s;

  &.hidden {
    opacity: 0;
    transform: translateY(-20px);
  }

  .prize-badge {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 60px;
    background: rgba(0, 0, 0, 0.5);
    border: 2px solid $color-gold;
    border-radius: 16px;
    backdrop-filter: blur(10px);

    .prize-level {
      font-size: 24px;
      color: $color-gold;
      margin-bottom: 8px;
      text-shadow: $glow-gold;
    }

    .prize-name {
      font-size: 36px;
      color: $color-text-light;
      font-weight: bold;
    }
  }
}

.phase-indicator {
  position: absolute;
  bottom: 150px;
  left: 50%;
  transform: translateX(-50%);

  .phase-text {
    font-size: 20px;
    color: $color-text-muted;
    padding: 10px 30px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 30px;
    backdrop-filter: blur(10px);
  }
}

.winners-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  pointer-events: none;
  z-index: 100;
  // Constrain to scroll area (600x400 with padding)
  max-width: 560px;
  max-height: 360px;
  overflow-y: auto;

  .winners-title {
    font-size: 28px;
    margin-bottom: 20px;
    text-shadow: $glow-gold;
  }

  .winners-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 12px;
    padding: 0 10px;
  }

  .winner-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 16px;
    min-width: 80px;
    background: transparent;
    border: none;
    border-radius: 8px;

    .winner-name {
      font-size: 22px;
      color: $color-gold;
      font-weight: bold;
      margin-bottom: 4px;
      text-shadow: $glow-gold;
    }

    .winner-dept {
      font-size: 12px;
      color: $color-gold;
      opacity: 0.8;
    }
  }
}

.status-panel {
  position: absolute;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  backdrop-filter: blur(10px);

  .status-text {
    font-size: 18px;
    color: $color-gold;
    font-weight: bold;
  }

  .admin-hint {
    font-size: 12px;
    color: $color-text-muted;
    opacity: 0.7;
  }
}
</style>
