<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useLecturesStore } from '@/stores/lectures'
import { useAuthStore } from '@/stores/auth'
import GlassCard from '@/components/ui/GlassCard.vue'
import StatusBadge from '@/components/ui/StatusBadge.vue'
import ModalDialog from '@/components/ui/ModalDialog.vue'
import EmptyState from '@/components/ui/EmptyState.vue'

const lecturesStore = useLecturesStore()
const auth = useAuthStore()
const router = useRouter()
const activeTab = ref<'upcoming' | 'history'>('upcoming')
const cancelModal = ref(false)
const selectedId = ref<string | null>(null)

const upcoming = computed(() =>
  lecturesStore.registeredLectures.map((l) => ({ ...l, status: 'registered' })),
)

const history = computed(() => lecturesStore.all.filter((l) => l.status === 'completed'))

onMounted(async () => {
  if (!lecturesStore.all.length) await lecturesStore.fetchLectures()
  if (auth.user) await lecturesStore.fetchRegisteredForCurrentUser()
})

function openCancel(id: string) {
  selectedId.value = id
  cancelModal.value = true
}

async function confirmCancel() {
  if (selectedId.value) await lecturesStore.unregister(selectedId.value)
  cancelModal.value = false
}
</script>

<template>
  <div class="my-lectures page-content">
    <div class="header">
      <div>
        <h1 class="page-title">Мои записи</h1>
        <p class="text-secondary">
          Управляйте регистрациями, экспортируйте расписание и оставляйте отзывы.
        </p>
      </div>
      <button class="btn-secondary">Экспорт в календарь</button>
    </div>

    <div class="tabs">
      <button :class="{ active: activeTab === 'upcoming' }" @click="activeTab = 'upcoming'">
        Предстоящие
      </button>
      <button :class="{ active: activeTab === 'history' }" @click="activeTab = 'history'">
        История
      </button>
    </div>

    <div v-if="activeTab === 'upcoming'" class="list">
      <EmptyState
        v-if="!upcoming.length"
        title="У вас нет предстоящих лекций"
        subtitle="Выберите лекцию в каталоге и запишитесь на неё."
      />
      <GlassCard v-for="item in upcoming" :key="item.id" class="lecture-row">
        <div>
          <div class="lecture-title">{{ item.title }}</div>
          <div class="lecture-meta">
            {{ new Date(item.date).toLocaleDateString('ru-RU') }} {{ item.time }}
          </div>
          <div class="lecture-meta">
            {{ item.building }} {{ item.room ? `ауд. ${item.room}` : '' }}
          </div>
        </div>
        <div class="lecture-actions">
          <StatusBadge status="registered" />
          <button class="btn-secondary btn-sm">Добавить в календарь</button>
          <button class="btn-danger btn-sm" @click="openCancel(item.id)">Отменить</button>
        </div>
      </GlassCard>
    </div>

    <div v-else class="list">
      <EmptyState
        v-if="!history.length"
        title="История пока пуста"
        subtitle="Завершённые лекции появятся здесь после посещения."
      />
      <GlassCard v-for="item in history" :key="item.id" class="lecture-row">
        <div>
          <div class="lecture-title">{{ item.title }}</div>
          <div class="lecture-meta">
            {{ new Date(item.date).toLocaleDateString('ru-RU') }} {{ item.time }}
          </div>
          <div class="lecture-meta">
            {{ item.building }} {{ item.room ? `ауд. ${item.room}` : '' }}
          </div>
        </div>
        <div class="lecture-actions">
          <StatusBadge :status="item.status ?? 'completed'" />
          <button class="btn-primary btn-sm" @click="router.push(`/review/${item.id}`)">
            Оставить отзыв
          </button>
        </div>
      </GlassCard>
    </div>

    <ModalDialog v-model="cancelModal" title="Отменить запись?" icon="alert-triangle" size="sm">
      <p>
        Вы уверены, что хотите отменить запись на лекцию? Место будет освобождено для других
        студентов.
      </p>
      <template #footer>
        <button class="btn-secondary" type="button" @click="cancelModal = false">Нет</button>
        <button class="btn-danger" type="button" @click="confirmCancel">Да, отменить</button>
      </template>
    </ModalDialog>
  </div>
</template>

<style scoped>
.my-lectures {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}
.tabs {
  display: inline-flex;
  width: fit-content;
  border: 1px solid var(--color-border-glass);
  border-radius: 12px;
  overflow: hidden;
}
.tabs button {
  background: rgba(255, 255, 255, 0.7);
  border: none;
  padding: 8px 18px;
  font-size: 13px;
  min-width: 110px;
  text-align: center;
  cursor: pointer;
  color: var(--color-text-secondary);
}
.tabs button.active {
  background: rgba(34, 197, 94, 0.18);
  color: var(--color-primary-dark);
  font-weight: 600;
}
.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.lecture-row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.lecture-title {
  font-weight: 700;
  margin-bottom: 4px;
}
.lecture-meta {
  font-size: 13px;
  color: var(--color-text-secondary);
}
.lecture-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}
.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}
</style>
