<script setup lang="ts">
import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usersApi } from '@/api'
import { downloadFile } from '@/utils/downloadFile'
import { useLecturesStore } from '@/stores/lectures'
import { useUserStore } from '@/stores/user'
import GlassCard from '@/components/ui/GlassCard.vue'
import LectureCard from '@/components/ui/LectureCard.vue'
import StatusBadge from '@/components/ui/StatusBadge.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import EnrollmentLimitModal from '@/components/ui/EnrollmentLimitModal.vue'

const route = useRoute()
const router = useRouter()
const lecturesStore = useLecturesStore()
const userStore = useUserStore()
const addToast = inject('addToast') as
  | ((message: string, type?: 'success' | 'error' | 'info') => void)
  | undefined
const enrollmentLimitModalOpen = ref(false)

const lectureId = computed(() => String(route.params.id))
const lecture = computed(() => lecturesStore.all.find((l) => l.id === lectureId.value))
const isRegistered = computed(() =>
  lecture.value ? lecturesStore.isRegistered(lecture.value.id) : false,
)
const slotRegistrationDisabled = computed(
  () => !userStore.hasEnrollmentSlotAvailable && !isRegistered.value,
)
const isAttended = computed(() => lecture.value?.status === 'completed')

const similarLectures = computed(() =>
  lecturesStore.all.filter((l) => l.id !== lectureId.value).slice(0, 3),
)

onMounted(async () => {
  if (!lecturesStore.all.length) await lecturesStore.fetchLectures()
  await lecturesStore.fetchLecture(lectureId.value)
})

async function downloadLectureIcs(id: string) {
  try {
    const blob = await usersApi.downloadEnrollmentIcs(id)
    downloadFile(blob, `lecture-${id}.ics`)
    addToast?.("Файл календаря скачан", "success")
  } catch (err) {
    addToast?.(err instanceof Error ? err.message : "Не удалось скачать .ics", "error")
  }
}

async function registerLecture() {
  if (!lecture.value) return
  if (slotRegistrationDisabled.value) {
    enrollmentLimitModalOpen.value = true
    return
  }

  try {
    await lecturesStore.register(lecture.value.id)
    addToast?.('Вы записаны на лекцию.', 'success')
  } catch (err) {
    if (err instanceof Error && err.message.includes('Лимит записей достигнут')) {
      enrollmentLimitModalOpen.value = true
      return
    }
    addToast?.(err instanceof Error ? err.message : 'Не удалось записаться на лекцию.', 'error')
  }
}
</script>

<template>
  <div v-if="lecturesStore.loading && !lecture" class="lecture-detail page-content">
    <GlassCard>
      <div class="text-secondary">Загружаем лекцию...</div>
    </GlassCard>
  </div>

  <div v-else-if="!lecture" class="lecture-detail page-content">
    <EmptyState
      title="Лекция не найдена"
      :subtitle="lecturesStore.error ?? 'Попробуйте открыть каталог и выбрать лекцию заново.'"
    />
  </div>

  <div v-else class="lecture-detail page-content">
    <div class="header">
      <div>
        <div class="breadcrumb">Каталог / {{ lecture.title }}</div>
        <h1 class="page-title">{{ lecture.title }}</h1>
        <p class="text-secondary">{{ lecture.description }}</p>
      </div>
      <div class="actions">
        <button
          v-if="!isRegistered"
          class="btn-primary"
          :disabled="lecture.freeSeats === 0 || lecture.registrationClosed"
          @click="registerLecture"
        >
          Записаться
        </button>
        <button v-else class="btn-secondary" @click="lecturesStore.unregister(lecture.id)">
          Отменить запись
        </button>
        <button class="btn-secondary" @click="downloadLectureIcs(lecture.id)">Скачать .ics</button>
        <button v-if="isAttended" class="btn-primary" @click="router.push(`/review/${lecture.id}`)">
          Оставить отзыв
        </button>
      </div>
    </div>

    <div class="info-grid">
      <GlassCard>
        <div class="info-section">
          <h3>Преподаватель</h3>
          <div class="info-value">
            {{ lecture.teacher
            }}<span v-if="lecture.teacherTitle"> {{ lecture.teacherTitle }}</span>
          </div>
          <div class="info-sub">
            {{ [lecture.department, lecture.institute].filter(Boolean).join(', ') }}
          </div>
        </div>
        <div class="info-section">
          <h3>Детали занятия</h3>
          <div class="info-value">
            {{ new Date(lecture.date).toLocaleDateString('ru-RU') }} {{ lecture.time }}
          </div>
          <div class="info-sub">Длительность: {{ lecture.duration }} мин</div>
          <div class="info-sub">
            Локация: {{ lecture.building }} {{ lecture.room ? `ауд. ${lecture.room}` : '' }}
          </div>
        </div>
        <div class="info-section">
          <h3>Места</h3>
          <div class="info-value">
            Записано {{ lecture.enrolledSeats }} из {{ lecture.totalSeats }}
          </div>
          <StatusBadge
            :status="
              lecture.registrationClosed ? 'closed' : lecture.freeSeats === 0 ? 'full' : 'open'
            "
          />
        </div>
        <div class="info-section">
          <h3>Теги</h3>
          <div class="tags">
            <span class="tag-chip" v-for="tag in lecture.tags" :key="tag">{{ tag }}</span>
          </div>
        </div>
      </GlassCard>
    </div>

    <section>
      <h2 class="section-title">Похожие лекции</h2>
      <div class="cards-grid">
        <LectureCard v-for="l in similarLectures" :key="l.id" :lecture="l" />
      </div>
    </section>

    <EnrollmentLimitModal v-model="enrollmentLimitModalOpen" />
  </div>
</template>

<style scoped>
.lecture-detail {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.breadcrumb {
  font-size: 12px;
  color: var(--color-text-secondary);
  margin-bottom: 6px;
}
.header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
}
.actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 16px;
}
.info-section {
  margin-bottom: 16px;
}
.info-section:last-child {
  margin-bottom: 0;
}
.info-section h3 {
  font-size: 14px;
  margin-bottom: 8px;
}
.info-value {
  font-weight: 700;
}
.info-sub {
  font-size: 13px;
  color: var(--color-text-secondary);
  margin-top: 4px;
}
.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}
</style>
