<template>
  <div class="dashboard">
    <div class="dashboard__main">
      <!-- اطلاعات مدرسه -->
      <section class="dashboard__section">
        <BoxedIconTitleBlock title="اطلاعات مدرسه" desc="آخرین اطلاعات مدرسه شما.">
          <template #icon>
            <SvgIcon name="heart" :size="24" color="var(--color-primary)" />
          </template>
        </BoxedIconTitleBlock>

        <SkeletonLoaderBlock v-if="isLoading" :rows="2" :cols-per-row="3" />
        <div v-else class="dashboard__stats">
          <DashboardStatCard
            v-for="(stat, i) in institutionStats"
            :key="i"
            :icon="stat.icon"
            :label="stat.label"
            :value="stat.value"
            :unit="stat.unit"
            :subtitle="stat.subtitle"
            :to="stat.to"
          />
        </div>
      </section>

      <!-- آخرین فعالیت ها -->
      <section class="dashboard__section">
        <BoxedIconTitleBlock
          title="آخرین فعالیت ها"
          desc="گزارشی از جدیدترین افراد ثبت نام شده و درخواست‌ها."
        >
          <template #icon>
            <SvgIcon name="heart" :size="24" color="var(--color-primary)" />
          </template>
        </BoxedIconTitleBlock>

        <SkeletonLoaderBlock v-if="isLoading" :rows="2" :cols-per-row="3" />
        <div v-else class="dashboard__activities">
          <DashboardActivityGroup
            v-for="(act, i) in activities"
            :key="i"
            circle
            thumb-icon="user"
            :pill-icon="act.pillIcon"
            :pill-label="act.pillLabel"
            :title="act.title"
            :meta="act.meta"
            :meta-icon="act.metaIcon"
            :avatar-url="act.avatarUrl"
          />
        </div>
      </section>
    </div>

    <aside class="dashboard__aside">
      <SkeletonLoaderBlock v-if="isLoading" :rows="2" :cols-per-row="1" />
      <DashboardProfileCard
        v-else
        :name="profile.name"
        :location="profile.location"
        :avatar-url="profile.avatarUrl"
        :stats="profile.stats"
      />
      <DashboardCalendar :month-label="calendar.month" :days="calendar.days" />
    </aside>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { toFaDigits, formatJalaaliMeta } from '@/utils/persian'
import { useTehranCalendar } from '@/composables/useTehranCalendar'
import { useAdminDashboardQuery } from '@/services/query/admin-dashboard'
import DashboardStatCard from '@/components/dashboard/DashboardStatCard.vue'
import DashboardCalendar from '@/components/dashboard/DashboardCalendar.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import DashboardProfileCard from '@/components/dashboard/DashboardProfileCard.vue'
import DashboardActivityGroup from '@/components/dashboard/DashboardActivityGroup.vue'

const { data, isLoading } = useAdminDashboardQuery()

const dashboard = computed(() => data.value?.data ?? {})

const ROLE_LABELS = {
  admin: 'مدیر سیستم',
  teacher: 'استاد',
  counselor: 'مشاور',
  missionary: 'مبلغ',
  student: 'دانش‌پژوه',
}
const ACCESS_LABELS = {
  full: 'کامل',
  limited: 'محدود',
}

const institutionStats = computed(() => {
  const stats = dashboard.value.stats ?? {}
  return [
    {
      icon: 'users-three',
      label: 'مجموع کل متقاضیان',
      value: toFaDigits(stats.totalApplicants ?? 0),
      unit: 'نفر',
      subtitle: 'احراز شده و نشده',
      to: { name: 'admin-users' },
    },
    {
      icon: 'clock',
      label: 'تعداد کاربران در انتظار ارزیابی',
      value: toFaDigits(stats.awaitingEvaluation ?? 0),
      unit: 'نفر',
      subtitle: 'در انتظار ارزیابی',
      to: { name: 'admin-user-verification' },
    },
    {
      icon: 'book',
      label: 'آمار طلبه‌های ترم ۱',
      value: toFaDigits(stats.term1Students ?? 0),
      unit: 'نفر',
      subtitle: 'ترم اول',
      to: { name: 'admin-terms' },
    },
    {
      icon: 'book',
      label: 'آمار طلبه‌های ترم ۲',
      value: toFaDigits(stats.term2Students ?? 0),
      unit: 'نفر',
      subtitle: 'ترم دوم',
      to: { name: 'admin-terms' },
    },
    {
      icon: 'book',
      label: 'آمار طلبه‌های ترم ۳',
      value: toFaDigits(stats.term3Students ?? 0),
      unit: 'نفر',
      subtitle: 'ترم سوم',
      to: { name: 'admin-terms' },
    },
    {
      icon: 'graduation-cap',
      label: 'آمار فارغ‌التحصیلان',
      value: toFaDigits(stats.graduates ?? 0),
      unit: 'نفر',
      subtitle: 'فارغ‌التحصیل',
      to: { name: 'admin-users' },
    },
  ]
})

const activities = computed(() => {
  const list = []
  const registration = dashboard.value.recentRegistrations?.[0]
  if (registration) {
    list.push({
      pillIcon: 'user',
      pillLabel: 'آخرین افراد ثبت نام شده',
      title: registration.name,
      avatarUrl: registration.avatarUrl ?? '',
      metaIcon: 'calendar',
      meta: [
        {
          label: 'تاریخ ثبت نام:',
          value: formatJalaaliMeta(registration.registeredAt),
          numeric: true,
        },
      ],
    })
  }
  const advise = dashboard.value.recentAdviseRequests?.[0]
  if (advise) {
    list.push({
      pillIcon: 'chat',
      pillLabel: 'اخرین درخواست مشاوره',
      title: advise.studentName,
      avatarUrl: advise.avatarUrl ?? '',
      metaIcon: 'calendar',
      meta: [
        { label: 'تاریخ درخواست:', value: formatJalaaliMeta(advise.createdAt), numeric: true },
      ],
    })
  }
  const service = dashboard.value.recentServiceRequests?.[0]
  if (service) {
    list.push({
      pillIcon: 'users-three',
      pillLabel: 'اخرین درخواست خدمات',
      title: service.studentName,
      avatarUrl: service.avatarUrl ?? '',
      metaIcon: 'calendar',
      meta: [
        { label: 'تاریخ درخواست:', value: formatJalaaliMeta(service.createdAt), numeric: true },
      ],
    })
  }
  return list
})

const profile = computed(() => {
  const info = dashboard.value.profile ?? {}
  return {
    name: info.name ?? '',
    avatarUrl: info.avatarUrl ?? '',
    location: [info.city || info.province, 'ایران'].filter(Boolean).join('، '),
    stats: [
      { label: 'نقش', value: ROLE_LABELS[info.role] ?? info.role ?? '' },
      { label: 'سطح دسترسی', value: ACCESS_LABELS[info.accessLevel] ?? info.accessLevel ?? '' },
      { label: 'تعداد تیکت‌های باز', value: toFaDigits(info.openTickets ?? 0) },
    ],
  }
})

const calendar = useTehranCalendar()
</script>

<style lang="scss" scoped>
.dashboard {
  display: flex;
  flex-direction: column-reverse;
  gap: 2rem;

  @media (min-width: 1024px) {
    flex-direction: row;
    align-items: flex-start;
  }

  &__main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }

  &__section {
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
  }

  &__stats {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.875rem;

    @media (min-width: 640px) {
      grid-template-columns: repeat(3, 1fr);
    }
  }

  &__activities {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1.25rem;

    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr);
    }
  }

  &__aside {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;

    @media (min-width: 1024px) {
      width: clamp(21rem, 26vw, 24rem);
      flex-shrink: 0;
      border-inline-start: 1px solid #e6e6e6;
      padding-inline-start: 2rem;
    }
  }
}
</style>
