<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="1" :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"
          />
        </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 formatThousands = (value) => {
  const n = Number(value ?? 0)
  return n >= 1000
    ? { value: toFaDigits(Math.round(n / 1000)), unit: 'هزار' }
    : { value: toFaDigits(n), unit: 'نفر' }
}

const institutionStats = computed(() => {
  const stats = dashboard.value.stats ?? {}
  const users = formatThousands(stats.activeUsers)
  return [
    {
      icon: 'user',
      label: 'آمار کلی کاربران',
      value: users.value,
      unit: users.unit,
      subtitle: 'کاربر فعال',
    },
    {
      icon: 'video',
      label: 'دوره های ایجاد شده',
      value: toFaDigits(stats.coursesCreated ?? 0),
      unit: 'دوره',
      subtitle: 'ایجاد شده',
    },
    {
      icon: 'shopping-bag',
      label: 'دوره های فروش رفته',
      value: toFaDigits(stats.coursesSold ?? 0),
      unit: 'عدد',
      subtitle: 'دوره فروش رفته',
    },
  ]
})

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: 19.625rem;
      flex-shrink: 0;
      border-inline-start: 1px solid #e6e6e6;
      padding-inline-start: 2rem;
    }
  }
}
</style>
