<template>
  <Layout>
    <template #main>
      <v-card class="mb-6" variant="flat">
        <v-card-title class="text-primary">現場量測</v-card-title>

        <v-card-subtitle class="text-grey-darken-3">
          在各量測站出示此頁面，由技術人員登錄數據
        </v-card-subtitle>
      </v-card>

      <!-- 報到活動資訊 -->
      <v-card v-if="activeAppointment" class="rounded-xl elevation-3 mb-6" color="surface">
        <v-card-text>
          <div class="d-flex align-center justify-space-between mb-3">
            <span class="text-title-small font-weight-bold text-primary">
              <v-icon class="mr-1" icon="mdi-map-marker-radius" />
              現場檢測站：{{ activeAppointment.location.split(' ')[0] }}
            </span>

            <v-chip class="font-weight-black" color="success" size="small" variant="flat">
              已報到
            </v-chip>
          </div>

          <h2 class="text-title-large font-weight-black text-grey-darken-4 mb-2">
            {{ activeAppointment.title }}
          </h2>

          <div class="text-title-small text-grey">日期：{{ activeAppointment.date }}</div>

          <!-- 量測總進度條 -->
          <div class="mt-4">
            <div class="d-flex justify-space-between align-center mb-1">
              <span class="text-title-small font-weight-bold text-grey-darken-2">測量站點完成度</span>

              <span class="text-title-small font-weight-bold text-primary">{{ completedCount }} / {{ totalCount }} ({{ progressPercent }}%)</span>
            </div>

            <v-progress-linear
              v-model="progressPercent"
              class="elevation-1"
              color="accent"
              height="10"
              rounded
              striped
            />
          </div>
        </v-card-text>
      </v-card>

      <!-- 未報到提示 -->
      <v-card v-else class="rounded-xl elevation-3 pa-6 text-center mb-6" color="surface">
        <v-icon class="mb-3" color="warning" icon="mdi-qrcode-scan" size="64" />
        <h3 class="text-title-medium font-weight-bold mb-2">尚未在活動現場合對報到</h3>

        <p class="text-body-medium text-grey mb-4">
          請先前往「活動預約」頁面，出示您的報到條碼給現場志工進行核對。
        </p>

        <v-btn class="rounded-lg" color="primary" to="/appointment">前往查看預約活動</v-btn>
      </v-card>

      <!-- 快捷測試功能 (對 Demo 非常友善) -->

      <div v-if="activeAppointment && completedCount < totalCount" class="d-flex justify-center">
        <v-btn
          class="rounded-lg font-weight-bold text-white"
          color="secondary"
          @click="simulateAllMeasurements"
        >
          一鍵模擬完成
        </v-btn>
      </div>

      <!-- 11 個量測關卡列表 -->
      <div v-if="activeAppointment" class="mb-6">
        <h3 class="text-title-medium font-weight-black text-primary px-4 mb-3">關卡列表</h3>

        <v-row>
          <v-col v-for="(station, key) in store.measurements" :key="key" class="mb-2" cols="12">
            <v-card
              class="rounded-xl elevation-2 cursor-pointer transition-card"
              :class="{ 'border-success': station.completed, 'border-grey': !station.completed }"
              :to="`/checkin/${key}`"
            >
              <div class="d-flex align-center justify-space-between pa-4">
                <div class="d-flex align-center">
                  <v-avatar
                    class="mr-3 text-white"
                    :color="station.completed ? 'success' : 'grey-lighten-2'"
                    size="40"
                  >
                    <v-icon
                      :icon="station.completed ? 'mdi-check' : getStationIcon(key)"
                      size="20"
                    />
                  </v-avatar>

                  <div>
                    <div
                      class="font-weight-bold text-body-large"
                      :class="station.completed ? 'text-success' : 'text-grey-darken-4'"
                    >
                      {{ station.name }}
                    </div>
                    <!-- 已完成，顯示數值 -->
                    <div v-if="station.completed" class="text-title-small text-grey-darken-2">
                      {{ getMeasurementSummary(key, station.values) }}
                      <span class="ml-2 text-grey-lighten-1">| {{ station.time?.split(' ')[1] }}</span>
                    </div>
                    <!-- 未完成，顯示待測 -->
                    <div v-else class="text-title-small text-grey-darken-1">
                      等待技術人員檢測登錄
                    </div>
                  </div>
                </div>

                <div>
                  <v-icon color="grey-lighten-1" icon="mdi-chevron-right" />
                </div>
              </div>
            </v-card>
          </v-col>
        </v-row>
      </div>

      <!-- 底部產出報告按鈕 (當全部完成時顯示) -->
      <v-btn
        v-if="activeAppointment"
        block
        class="rounded-xl font-weight-bold text-white elevation-4 py-4 d-flex align-center justify-center mb-8"
        :color="completedCount === totalCount ? 'secondary' : 'grey-lighten-1'"
        :disabled="completedCount < totalCount"
        size="large"
        @click="generateReport"
      >
        <v-icon class="mr-2" icon="mdi-file-chart-outline" size="24" />
        產出個人健康力報告
      </v-btn>

      <!-- 報告生成成功彈窗 -->
      <v-dialog v-model="reportSuccessDialog" max-width="400" persistent>
        <v-card class="rounded-xl overflow-hidden text-center pa-6">
          <v-avatar class="mx-auto mb-4 elevation-3" color="success" size="72">
            <v-icon color="white" icon="mdi-check-all" size="40" />
          </v-avatar>

          <h2 class="text-h5 font-weight-black text-success mb-2">報告計算完成！</h2>

          <p class="text-body-2 text-grey-darken-2 mb-6">
            您的健康力五維雷達圖、與同齡區間的參考值以及健康力總分已成功計算更新。
          </p>

          <v-btn
            block
            class="rounded-lg py-2 font-weight-bold"
            color="primary"
            variant="flat"
            @click="goToDashboard"
          >
            看我的健康力儀表板
          </v-btn>
        </v-card>
      </v-dialog>
    </template>
  </Layout>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import Layout from '@/components/layout/DefaultLayout.vue'
import { useAppStore } from '@/stores/app'

const store = useAppStore()
const router = useRouter()
const reportSuccessDialog = ref(false)

// 尋找已報到的活動
const activeAppointment = computed(() => {
  return store.appointments.find(a => a.status === '已報到')
})

const completedCount = computed(() => store.completedStationsCount)
const totalCount = computed(() => store.totalStationsCount)
const progressPercent = computed(() => store.progressPercent)

function getStationIcon (code: string) {
  switch (code) {
    case 'BloodPressure': {
      return 'mdi-heart-flash'
    }
    case 'BodyFat': {
      return 'mdi-scale-bathroom'
    }
    case 'GripStrength': {
      return 'mdi-hand-back-left'
    }
    case 'Sit5x': {
      return 'mdi-human-male-height'
    }
    case 'Sit30s': {
      return 'mdi-chair-school'
    }
    case 'StepTest': {
      return 'mdi-run-fast'
    }
    case 'ArmTest': {
      return 'mdi-arm-flex'
    }
    case 'BackTest': {
      return 'mdi-human-stretching'
    }
    case 'SitReachTest': {
      return 'mdi-human-stretching'
    }
    case 'UpGo8ft': {
      return 'mdi-navigation'
    }
    case 'OneLegTest': {
      return 'mdi-scale-balance'
    }
    default: {
      return 'mdi-checkbox-blank-circle-outline'
    }
  }
}

function getMeasurementSummary (code: string, vals: Record<string, any>) {
  switch (code) {
    case 'BloodPressure': {
      return `收縮壓: ${vals.systolic} / 舒張壓: ${vals.diastolic} mmHg | 心率: ${vals.heartRate} bpm`
    }
    case 'BodyFat': {
      return `BMI: ${vals.bmi} | 體脂率: ${vals.bodyFatPct}%`
    }
    case 'GripStrength': {
      return `左手: ${vals.leftHand} kg | 右手: ${vals.rightHand} kg`
    }
    case 'Sit5x': {
      return `耗時: ${vals.durationSeconds} 秒`
    }
    case 'Sit30s': {
      return `次數: ${vals.count} 次`
    }
    case 'StepTest': {
      return `踏步: ${vals.count} 次`
    }
    case 'ArmTest': {
      return `屈舉: ${vals.count} 次`
    }
    case 'BackTest': {
      return `左手: ${vals.leftDistanceCm} cm | 右手: ${vals.rightDistanceCm} cm`
    }
    case 'SitReachTest': {
      return `伸展: ${vals.distanceCm} cm`
    }
    case 'UpGo8ft': {
      return `耗時: ${vals.durationSeconds} 秒`
    }
    case 'OneLegTest': {
      return `左腳: ${vals.leftSeconds} 秒 | 右腳: ${vals.rightSeconds} 秒`
    }
    default: {
      return '數據登錄成功'
    }
  }
}

// 模擬一鍵完成所有測量 (對 Demo 极為有用)
function simulateAllMeasurements () {
  // 自動將剩餘的 9 站填入合理健康的隨機值
  const m = store.measurements

  if (!m.GripStrength.completed) {
    store.saveMeasurement('GripStrength', { leftHand: 32, rightHand: 34 })
  }
  if (!m.Sit5x.completed) {
    store.saveMeasurement('Sit5x', { durationSeconds: 8.5 })
  }
  if (!m.Sit30s.completed) {
    store.saveMeasurement('Sit30s', { count: 18 })
  }
  if (!m.StepTest.completed) {
    store.saveMeasurement('StepTest', { count: 92 })
  }
  if (!m.ArmTest.completed) {
    store.saveMeasurement('ArmTest', { count: 20 })
  }
  if (!m.BackTest.completed) {
    store.saveMeasurement('BackTest', { leftDistanceCm: 2, rightDistanceCm: 3 })
  }
  if (!m.SitReachTest.completed) {
    store.saveMeasurement('SitReachTest', { distanceCm: 14 })
  }
  if (!m.UpGo8ft.completed) {
    store.saveMeasurement('UpGo8ft', { durationSeconds: 5.8 })
  }
  if (!m.OneLegTest.completed) {
    store.saveMeasurement('OneLegTest', { leftSeconds: 24, rightSeconds: 26 })
  }
}

function generateReport () {
  store.generateFinalReport()
  reportSuccessDialog.value = true
}

function goToDashboard () {
  reportSuccessDialog.value = false
  router.push('/')
}
</script>

<style scoped>
.transition-card {
  transition: all 0.2s ease;
  border-width: 1.5px !important;
}

.transition-card:hover {
  transform: translateY(-1.5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.border-success {
  border-color: rgba(76, 175, 80, 0.5) !important;
}

.border-grey {
  border-color: rgba(0, 0, 0, 0.08) !important;
}

.border-accent-light {
  border: 1px solid rgba(71, 194, 166, 0.2) !important;
}
</style>
