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

const router = useRouter();
const { isConnected, onlineUsers, lotteryState, onLotteryStateChange } = 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: 'iPhone 16 Pro Max' });
const winners = ref<Participant[]>([]);
const currentRound = ref(1);

// Prize configuration
const prizes = [
  { level: '特等奖', name: 'iPhone 16 Pro Max', winnerCount: 1 },
  { level: '一等奖', name: 'iPad Pro', winnerCount: 3 },
  { level: '二等奖', name: 'AirPods Pro', winnerCount: 5 },
  { level: '三等奖', name: '京东卡 500元', winnerCount: 10 },
];

// Mock participants (would come from API)
const mockParticipants: Participant[] = [
  { id: '1', name: '张三', department: '技术部', zodiac: 'horse', age: 28 },
  { id: '2', name: '李四', department: '产品部', zodiac: 'dragon', age: 32 },
  { id: '3', name: '王五', department: '设计部', zodiac: 'horse', age: 26 },
  { id: '4', name: '赵六', department: '市场部', zodiac: 'tiger', age: 35 },
  { id: '5', name: '钱七', department: '运营部', zodiac: 'horse', age: 29 },
  { id: '6', name: '孙八', department: '人事部', zodiac: 'rabbit', age: 31 },
  { id: '7', name: '周九', department: '财务部', zodiac: 'snake', age: 27 },
  { id: '8', name: '吴十', department: '销售部', zodiac: 'horse', age: 33 },
  { id: '9', name: '郑十一', department: '技术部', zodiac: 'monkey', age: 25 },
  { id: '10', name: '王十二', department: '产品部', zodiac: 'horse', age: 30 },
  { id: '11', name: '冯十三', department: '设计部', zodiac: 'rooster', age: 28 },
  { id: '12', name: '陈十四', department: '市场部', zodiac: 'dog', age: 34 },
  { id: '13', name: '褚十五', department: '运营部', zodiac: 'horse', age: 26 },
  { id: '14', name: '卫十六', department: '人事部', zodiac: 'pig', age: 29 },
  { id: '15', name: '蒋十七', department: '财务部', zodiac: 'rat', age: 31 },
  { id: '16', name: '沈十八', department: '销售部', zodiac: 'ox', age: 27 },
  { id: '17', name: '韩十九', department: '技术部', zodiac: 'horse', age: 32 },
  { id: '18', name: '杨二十', department: '产品部', zodiac: 'tiger', age: 28 },
  { id: '19', name: '朱廿一', department: '设计部', zodiac: 'rabbit', age: 25 },
  { id: '20', name: '秦廿二', department: '市场部', zodiac: 'horse', age: 30 },
];

// 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;
}

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

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

  // 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;

  // Pick random winners
  const prize = prizes[currentRound.value - 1];
  const eligibleParticipants = mockParticipants.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).map(p => p.id);

  lotteryMachine.revealWinners(winnerIds);
}

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

  currentRound.value = Math.min(4, currentRound.value + 1);
  currentPrize.value = {
    level: prizes[currentRound.value - 1].level,
    name: prizes[currentRound.value - 1].name,
  };
  winners.value = [];

  lotteryMachine.reset();
}

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

  currentRound.value = 1;
  currentPrize.value = { level: prizes[0].level, name: prizes[0].name };
  winners.value = [];

  lotteryMachine.reset();
}

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

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

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

  // Subscribe to lottery state changes from server
  unsubscribeLottery = onLotteryStateChange((state) => {
    if (state.phase === 'rolling' && currentPhase.value !== 'storm') {
      startRolling();
    }
  });
});

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>

      <!-- Control Panel -->
      <div class="control-panel">
        <button
          v-if="currentPhase === 'idle'"
          class="control-btn primary"
          @click="startGalaxy"
        >
          开始展示
        </button>

        <button
          v-if="currentPhase === 'galaxy'"
          class="control-btn primary"
          @click="startRolling"
        >
          开始抽奖
        </button>

        <button
          v-if="currentPhase === 'storm'"
          class="control-btn danger"
          @click="stopAndReveal"
        >
          停止抽奖
        </button>

        <button
          v-if="currentPhase === 'complete'"
          class="control-btn secondary"
          @click="nextRound"
          :disabled="currentRound >= 4"
        >
          下一轮
        </button>

        <button
          v-if="currentPhase === 'complete'"
          class="control-btn outline"
          @click="resetLottery"
        >
          重置
        </button>
      </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;

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

  .winners-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
    max-width: 800px;
  }

  .winner-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 30px;
    background: rgba(0, 0, 0, 0.7);
    border: 2px solid $color-gold;
    border-radius: 12px;
    backdrop-filter: blur(10px);

    .winner-name {
      font-size: 28px;
      color: $color-gold;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .winner-dept {
      font-size: 16px;
      color: $color-text-muted;
    }
  }
}

.control-panel {
  position: absolute;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20px;

  .control-btn {
    padding: 16px 40px;
    font-size: 20px;
    font-weight: bold;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    border: none;

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    &:hover:not(:disabled) {
      transform: scale(1.05);
    }

    &.primary {
      background: linear-gradient(135deg, $color-gold-dark, $color-gold);
      color: #000;
      box-shadow: $glow-gold;
    }

    &.danger {
      background: linear-gradient(135deg, $color-primary-dark, $color-primary);
      color: $color-text-light;
      box-shadow: $glow-red;
    }

    &.secondary {
      background: rgba($color-gold, 0.2);
      color: $color-gold;
      border: 2px solid $color-gold;
    }

    &.outline {
      background: transparent;
      color: $color-text-muted;
      border: 1px solid $color-text-muted;

      &:hover:not(:disabled) {
        border-color: $color-text-light;
        color: $color-text-light;
      }
    }
  }
}
</style>
