<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import GlassCard from '@/components/ui/GlassCard.vue'
import StatsWidget from '@/components/ui/StatsWidget.vue'
import StatusBadge from '@/components/ui/StatusBadge.vue'
import { lecturesApi, reviewsApi, syncApi, usersApi } from '@/api'
import type { LectureDto, SyncStatusDto, UserDto } from '@/api/types'

const users = ref<UserDto[]>([])
const lectures = ref<LectureDto[]>([])
const pendingReviewsCount = ref(0)
const syncStatus = ref<SyncStatusDto | null>(null)

const enrollmentCount = computed(() =>
  lectures.value.reduce((sum, lecture) => sum + lecture.enrollmentsCount, 0),
)
const syncMeta = computed(() =>
  syncStatus.value?.lastSyncAt
    ? `Последняя синхронизация: ${new Date(syncStatus.value.lastSyncAt).toLocaleString('ru-RU')}`
    : 'Синхронизация ещё не выполнялась',
)

onMounted(async () => {
  const [usersResult, lecturesResult, reviewsResult, syncResult] = await Promise.allSettled([
    usersApi.list({ PageSize: 100 }),
    lecturesApi.list({ PageSize: 100 }),
    reviewsApi.listPage({ Page: 1, PageSize: 1, LlmStatus: 'Pending' }),
    syncApi.status(),
  ])
  if (usersResult.status === 'fulfilled') users.value = usersResult.value
  if (lecturesResult.status === 'fulfilled') lectures.value = lecturesResult.value
  if (reviewsResult.status === 'fulfilled')
    pendingReviewsCount.value = reviewsResult.value.totalCount
  if (syncResult.status === 'fulfilled') syncStatus.value = syncResult.value
})
</script>

<template>
  <div class="admin-dashboard page-content">
    <h1 class="page-title">Дашборд администратора</h1>

    <div class="stats-row">
      <StatsWidget label="Пользователей" :value="users.length" icon="users" color="green" />
      <StatsWidget label="Лекций" :value="lectures.length" icon="books" color="aqua" />
      <StatsWidget label="Записей" :value="enrollmentCount" icon="calendar-event" color="orange" />
      <StatsWidget
        label="Отзывы на проверке"
        :value="pendingReviewsCount"
        icon="message-circle"
        color="purple"
      />
    </div>

    <div class="grid">
      <GlassCard>
        <div class="section-title">Состояние синхронизации расписания</div>
        <StatusBadge :status="syncStatus?.status ?? 'pending'" />
        <div class="sync-meta">{{ syncMeta }}</div>
        <div class="sync-error" v-if="syncStatus?.lastResult?.error">
          Ошибка: {{ syncStatus.lastResult.error }}
        </div>
      </GlassCard>
    </div>
  </div>
</template>

<style scoped>
.admin-dashboard {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 16px;
}
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 16px;
}
.sync-meta {
  font-size: 12px;
  color: var(--color-text-secondary);
  margin-top: 6px;
}
.sync-error {
  font-size: 12px;
  color: var(--color-error);
  margin-top: 8px;
}
</style>
