<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 performanceStats"
            :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="2" />
        <div v-else class="dashboard__activities">
          <div v-for="(act, i) in activities" :key="i" class="dashboard__activity">
            <div class="dashboard__pill">
              <SvgIcon :name="act.pillIcon" :size="'1.125rem'" class="dashboard__pill-icon" />
              <span class="dashboard__pill-label">{{ act.pillLabel }}</span>
            </div>
            <DashboardActivityCard :title="act.title" :meta="act.meta" :meta-icon="act.metaIcon" />
          </div>
        </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 { toJalaali } from '@/utils/date-utils'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import { useStudentDashboardQuery } from '@/services/query/student-dashboard'
import DashboardStatCard from '@/features/student/pages/components/DashboardStatCard.vue'
import DashboardCalendar from '@/features/student/pages/components/DashboardCalendar.vue'
import DashboardProfileCard from '@/features/student/pages/components/DashboardProfileCard.vue'
import DashboardActivityCard from '@/features/student/pages/components/DashboardActivityCard.vue'

const { data, isLoading } = useStudentDashboardQuery()

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

const toFaDigits = (value) => String(value ?? '').replace(/\d/g, (d) => '۰۱۲۳۴۵۶۷۸۹'[d])

const formatMetaDateTime = (iso) => {
  const match = String(iso ?? '').match(/^(\d{4})-(\d{2})-(\d{2})[\sT](\d{2}):(\d{2})/)
  if (!match) return ''
  const { jy, jm, jd } = toJalaali(Number(match[1]), Number(match[2]), Number(match[3]))
  return toFaDigits(`${jy}/${jm}/${jd}, ${Number(match[4])}:${match[5]}`)
}

const performanceStats = computed(() => {
  const stats = dashboard.value.stats ?? {}
  return [
    {
      icon: 'video',
      label: 'تعداد جلسات آموزشی گذرانده‌شده',
      value: toFaDigits(stats.attendedSessions ?? 0),
      unit: 'جلسه',
      subtitle: 'با موفقیت گذرانده شده',
      to: { name: 'student-terms' },
    },
    {
      icon: 'video',
      label: 'دوره های خریداری شده',
      value: toFaDigits(stats.enrolledTerms ?? 0),
      unit: 'دوره',
      subtitle: 'خریداری شده',
      to: { name: 'student-terms' },
    },
    {
      icon: 'clock',
      label: 'ساعات آموزشی سپری‌شده',
      value: toFaDigits(stats.hoursSpent ?? 0),
      unit: 'ساعت',
      subtitle: 'گذرانده شده',
      to: { name: 'student-terms' },
    },
  ]
})

const activities = computed(() => {
  const list = []
  const course = dashboard.value.lastEnrolledCourse
  if (course) {
    list.push({
      pillIcon: 'shopping-bag',
      pillLabel: 'آخرین دوره خریداری شده',
      title: course.title,
      metaIcon: 'calendar',
      meta: [
        { label: 'تاریخ شروع:', value: formatMetaDateTime(course.startsAt), numeric: true },
        { label: 'استاد:', value: course.teacher?.name ?? '' },
        { label: 'تاریخ پایان:', value: formatMetaDateTime(course.endsAt), numeric: true },
      ],
    })
  }
  const session = dashboard.value.lastWatchedSession
  if (session) {
    const sessionName =
      session.title?.replace(/^جلسه\s*/u, '') || toFaDigits(session.sessionNumber ?? '')
    list.push({
      pillIcon: 'video',
      pillLabel: 'اخرین جلسه دیده شده',
      title: session.courseTitle,
      metaIcon: 'video',
      meta: [
        { label: 'جلسه:', value: sessionName },
        { label: 'استاد:', value: session.teacher?.name ?? '' },
      ],
    })
  }
  return list
})

const profile = computed(() => {
  const info = dashboard.value.profile ?? {}
  const stats = dashboard.value.stats ?? {}
  return {
    name: info.name ?? '',
    avatarUrl: info.avatarUrl ?? '',
    location: [info.city || info.province, 'ایران'].filter(Boolean).join('، '),
    stats: [
      { label: 'مدت عضویت', value: toFaDigits(info.membershipDays ?? 0), unit: 'روز' },
      { label: 'دوره‌های تکمیل‌شده', value: toFaDigits(stats.completedCourses ?? 0), unit: 'عدد' },
      { label: 'دوره‌های فعال', value: toFaDigits(stats.activeCourses ?? 0), unit: 'عدد' },
    ],
  }
})

const WEEKDAY_NAMES = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه']
const MONTH_NAMES = [
  'فروردین',
  'اردیبهشت',
  'خرداد',
  'تیر',
  'مرداد',
  'شهریور',
  'مهر',
  'آبان',
  'آذر',
  'دی',
  'بهمن',
  'اسفند',
]
const GREGORIAN_WEEKDAYS = ['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']
const DAY_MS = 24 * 60 * 60 * 1000

const buildTehranCalendar = () => {
  const parts = new Intl.DateTimeFormat('en-US', {
    timeZone: 'Asia/Tehran',
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    weekday: 'short',
  }).formatToParts(new Date())
  const part = (type) => parts.find((p) => p.type === type)?.value
  const todayIndex = GREGORIAN_WEEKDAYS.indexOf(part('weekday'))
  const todayUtc = Date.UTC(Number(part('year')), Number(part('month')) - 1, Number(part('day')))
  const weekStartUtc = todayUtc - todayIndex * DAY_MS

  const today = new Date(todayUtc)
  const { jm } = toJalaali(today.getUTCFullYear(), today.getUTCMonth() + 1, today.getUTCDate())

  const days = WEEKDAY_NAMES.map((weekday, i) => {
    const date = new Date(weekStartUtc + i * DAY_MS)
    const { jd } = toJalaali(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate())
    return { weekday, day: toFaDigits(jd), selected: i === todayIndex }
  })

  return { month: `${MONTH_NAMES[jm - 1]} ماه`, days }
}

const calendar = buildTehranCalendar()
</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(2, 1fr);
    }
  }

  &__activity {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  &__pill {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 0.5rem;
    padding: 0.75rem 1.25rem;
    background: rgba(255, 255, 255, 58%);
    box-shadow: 0 6.75px 19.425px rgba(0, 0, 0, 4%);
    border-radius: 0.9375rem;
  }

  &__pill-icon {
    order: 2;
  }

  &__pill-label {
    order: 1;
    font-family: var(--font-family-fa);
    font-weight: 500;
    font-size: 1.125rem;
    color: #4b4b4b;
  }

  &__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>
