<script setup>
import { ref, computed, onMounted } from 'vue'
import { useTranslation } from 'i18next-vue'
import { useRouter, useRoute } from 'vue-router'
import { useCombos } from '../composables/useCombos.js'
import { useJsonExport } from '../composables/useJsonExport.js'
import { useKeyboardShortcut } from '../composables/useKeyboardShortcut.js'
import { renderMarkdown } from '../utils/markdown.js'
import { sessionRepository } from '../db/repositories/sessionRepository.js'

const { t } = useTranslation()
const router = useRouter()
const route = useRoute()
const { getById, remove } = useCombos()
const { exportCombo } = useJsonExport()

const combo = ref(null)
const loading = ref(true)

const comboId = computed(() => route.params.id)

onMounted(async () => {
  const data = await getById(comboId.value)
  if (!data) {
    router.replace({ name: 'combos' })
    return
  }
  combo.value = data
  loading.value = false
})

function goToEdit() {
  router.push({ name: 'combo-edit', params: { id: comboId.value } })
}

useKeyboardShortcut('e', goToEdit)
useKeyboardShortcut('escape', goBack, false)

function goBack() {
  router.push({ name: 'combos' })
}

function goToExercise(exerciseId) {
  router.push({ name: 'exercise-detail', params: { id: exerciseId } })
}

async function onDelete() {
  if (!combo.value) return
  const sessionCount = await sessionRepository.countSessionsUsingItem(comboId.value, 'combo')
  let msg = t('combos.deleteConfirm', { title: combo.value.title })
  if (sessionCount > 0) {
    msg += '\n\n' + t('combos.deleteConfirmUsage', { sessions: sessionCount })
  }
  const confirmed = window.confirm(msg)
  if (!confirmed) return
  await remove(comboId.value)
  router.push({ name: 'combos' })
}

async function onExport() {
  await exportCombo(comboId.value)
}
</script>

<template>
  <Teleport to="#actionbar-actions" defer>
    <button
      data-testid="combo-back-btn"
      :title="$t('combos.title') + ' ' + $t('shortcuts.back')"
      :aria-label="$t('combos.title')"
      @click="goBack"
    >
      <i class="bi bi-arrow-left"></i>
    </button>
    <button
      data-testid="combo-export-single-btn"
      :title="$t('export.combo')"
      :aria-label="$t('export.combo')"
      @click="onExport"
    >
      <i class="bi bi-download"></i>
    </button>
    <button
      data-testid="combo-edit-btn"
      :title="$t('combos.edit') + ' ' + $t('shortcuts.edit')"
      :aria-label="$t('combos.edit')"
      @click="goToEdit"
    >
      <i class="bi bi-pencil"></i>
    </button>
    <button
      data-testid="combo-delete-btn"
      :title="$t('combos.delete')"
      :aria-label="$t('combos.delete')"
      @click="onDelete"
    >
      <i class="bi bi-trash"></i>
    </button>
  </Teleport>

  <div class="combo-detail-view">
    <p v-if="loading" class="text-muted">{{ $t('app.loading') }}</p>

    <template v-else-if="combo">
      <!-- Title -->
      <h2 data-testid="combo-detail-title">{{ combo.title }}</h2>

      <!-- Description -->
      <div
        v-if="combo.description"
        class="combo-description"
        data-testid="combo-detail-description"
        v-html="renderMarkdown(combo.description)"
      />

      <!-- Meta -->
      <div class="combo-meta">
        <span class="badge badge-type" data-testid="combo-detail-type">
          {{ $t(`combos.types.${combo.type.toLowerCase()}`) }}
        </span>
      </div>

      <!-- Timer config -->
      <div
        v-if="combo.type !== 'NONE' && combo.timer_config && Object.keys(combo.timer_config).length"
        class="timer-config-section"
      >
        <h3>{{ $t('combos.timerConfig') }}</h3>
        <dl class="timer-config-list">
          <template v-if="combo.type === 'EMOM'">
            <dt>{{ $t('combos.timer.emomDuration') }}</dt>
            <dd data-testid="combo-detail-emom-duration">
              {{ combo.timer_config.duration || '—' }} {{ $t('combos.timer.minutes') }}
            </dd>
          </template>
          <template v-else-if="combo.type === 'AMRAP'">
            <dt>{{ $t('combos.timer.amrapDuration') }}</dt>
            <dd data-testid="combo-detail-amrap-duration">
              {{ combo.timer_config.duration || '—' }} {{ $t('combos.timer.minutes') }}
            </dd>
          </template>
          <template v-else-if="combo.type === 'TABATA'">
            <dt>{{ $t('combos.timer.tabataRounds') }}</dt>
            <dd data-testid="combo-detail-tabata-rounds">
              {{ combo.timer_config.rounds || '—' }} {{ $t('combos.timer.rounds') }}
            </dd>
          </template>
        </dl>
      </div>

      <!-- Exercises -->
      <div v-if="combo.exercises && combo.exercises.length" class="exercises-section">
        <h3>{{ $t('combos.form.exercises') }}</h3>
        <ol class="combo-exercise-list">
          <li
            v-for="(ex, index) in combo.exercises"
            :key="'ex-' + index"
            class="combo-exercise-item"
            :data-testid="'combo-detail-exercise-' + index"
          >
            <span class="combo-exercise-number">{{ index + 1 }}</span>
            <a
              class="combo-exercise-title"
              :data-testid="'combo-detail-exercise-link-' + index"
              @click="goToExercise(ex.exercise_id)"
            >
              {{ ex.title }}
            </a>
            <span
              class="combo-exercise-details"
              :data-testid="'combo-detail-exercise-details-' + index"
            >
              <span>{{ ex.default_reps }} {{ $t('exercises.reps') }}</span>
              <span>{{ ex.default_weight }} {{ $t('exercises.weight') }}</span>
            </span>
          </li>
        </ol>
      </div>
    </template>
  </div>
</template>

<style scoped>
.combo-detail-view {
  max-width: 800px;
}

.combo-detail-view h2 {
  font-size: 22px;
  margin-bottom: 8px;
}

.combo-description {
  font-size: 15px;
  line-height: 1.5;
  margin-bottom: 12px;
}

.combo-description :deep(p) {
  margin: 0 0 8px;
}

.combo-description :deep(p:last-child) {
  margin-bottom: 0;
}

.combo-description :deep(ul),
.combo-description :deep(ol) {
  margin: 0 0 8px;
  padding-left: 20px;
}

.combo-description :deep(code) {
  font-family: monospace;
  font-size: 13px;
  background: var(--color-surface, #f4f4f4);
  padding: 1px 4px;
  border-radius: 3px;
}

.combo-description :deep(pre) {
  background: var(--color-surface, #f4f4f4);
  padding: 8px;
  border-radius: 4px;
  overflow-x: auto;
  margin-bottom: 8px;
}

.combo-description :deep(strong) {
  font-weight: 600;
}

.combo-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 13px;
  background-color: var(--btn-primary-bg);
  color: var(--btn-primary-color);
}

.badge-type {
  background-color: var(--front-color2);
}

.timer-config-section {
  margin-bottom: 20px;
}

.timer-config-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.timer-config-list {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 4px 16px;
  margin: 0;
  padding: 0;
}

.timer-config-list dt {
  font-weight: 600;
  font-size: 14px;
}

.timer-config-list dd {
  margin: 0;
  font-size: 14px;
}

.exercises-section {
  margin-bottom: 20px;
}

.exercises-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.combo-exercise-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.combo-exercise-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 4px;
  border-bottom: 1px solid var(--border-color);
}

.combo-exercise-number {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: var(--btn-primary-bg);
  color: var(--btn-primary-color);
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.combo-exercise-title {
  font-size: 14px;
  color: var(--btn-primary-bg);
  cursor: pointer;
  text-decoration: none;
}

.combo-exercise-title:hover {
  text-decoration: underline;
}

.combo-exercise-details {
  display: flex;
  gap: 8px;
  font-size: 13px;
  color: var(--color-text-muted);
  margin-left: auto;
}

.combo-exercise-details span {
  white-space: nowrap;
}

.combo-exercise-title:hover {
  text-decoration: underline;
}
</style>
