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

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

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

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

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

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

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

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

function goToExecute() {
  router.push({ name: 'session-execute', params: { id: sessionId.value } })
}

function goToItem(item) {
  if (item.item_type === 'exercise') {
    router.push({ name: 'exercise-detail', params: { id: item.item_id } })
  } else {
    router.push({ name: 'combo-detail', params: { id: item.item_id } })
  }
}

function getItemTypeLabel(itemType) {
  return itemType === 'exercise' ? t('sessions.itemType.exercise') : t('sessions.itemType.combo')
}

async function onDelete() {
  if (!session.value) return
  const [count, collectionCount] = await Promise.all([
    executionLogRepository.countLogsBySession(sessionId.value),
    collectionRepository.countCollectionsUsingSession(sessionId.value),
  ])
  let msg =
    count > 0
      ? t('sessions.deleteConfirmWithHistory', { title: session.value.title, count })
      : t('sessions.deleteConfirm', { title: session.value.title })
  if (collectionCount > 0) {
    msg += '\n\n' + t('sessions.deleteConfirmUsage', { collections: collectionCount })
  }
  const confirmed = window.confirm(msg)
  if (!confirmed) return
  await remove(sessionId.value)
  router.push({ name: 'sessions' })
}

async function onExport() {
  await exportSession(sessionId.value)
}
</script>

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

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

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

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

      <!-- Items -->
      <div v-if="session.items && session.items.length" class="items-section">
        <h3>{{ $t('sessions.form.items') }}</h3>
        <ol class="session-item-list">
          <li
            v-for="(item, index) in session.items"
            :key="'item-' + index"
            class="session-item"
            :data-testid="'session-detail-item-' + index"
          >
            <span class="session-item-number">{{ index + 1 }}</span>
            <span class="session-item-type">{{ getItemTypeLabel(item.item_type) }}</span>
            <a
              class="session-item-title"
              :data-testid="'session-detail-item-link-' + index"
              @click="goToItem(item)"
            >
              {{ item.title }}
            </a>
            <span
              class="session-item-details"
              :data-testid="'session-detail-item-details-' + index"
            >
              <span v-if="item.combo_type === 'AMRAP'">
                {{ item.repetitions }} {{ $t('combos.timer.minutes') }}
              </span>
              <span v-else>{{ item.repetitions }} {{ $t('exercises.reps') }}</span>
              <span v-if="item.item_type === 'exercise'"
                >{{ item.weight }} {{ $t('exercises.weight') }}</span
              >
              <span v-else>0 {{ $t('exercises.weight') }}</span>
            </span>
          </li>
        </ol>
      </div>
    </template>
  </div>
</template>

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

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

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

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

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

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

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

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

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

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

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

.session-item-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

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

.session-item-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;
}

.session-item-type {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: var(--front-color2);
  color: var(--btn-primary-color);
  flex-shrink: 0;
}

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

.session-item-title:hover {
  text-decoration: underline;
}

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

.session-item-details span {
  white-space: nowrap;
}
</style>
