<template>
  <BasicModal
    title="جزئیات ترم"
    title-en="Term Details"
    width="95%"
    max-width="80rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div v-if="!term" class="term-details">
        <p class="term-details__loading">در حال بارگذاری…</p>
      </div>
      <div v-else class="term-details">
        <section class="term-details__section">
          <div class="term-details__overview">
            <div class="term-details__image">
              <img v-if="term.coverUrl" :src="term.coverUrl" :alt="term.title" />
              <SvgIcon v-else name="book" :size="32" color="#bcbcbc" />
            </div>
            <div class="term-details__overview-grid">
              <LineInfoBlock title="عنوان ترم" :desc="term.title || '-'" />
              <LineInfoBlock
                title="تاریخ ایجاد"
                :numeric-desc="formatJalaaliDate(term.createdAt) || '-'"
              />
              <LineInfoBlock title="تعداد طلبه‌ها" :numeric-desc="term.studentsCount ?? 0" />
              <LineInfoBlock title="تعداد دوره‌ها" :numeric-desc="term.coursesCount ?? 0" />
              <LineInfoBlock title="وضعیت" :desc="term.isActive ? 'فعال' : 'غیرفعال'" />
              <div v-if="term.description" class="term-details__cell--full">
                <LineInfoBlock title="توضیحات" :desc="term.description" />
              </div>
            </div>
          </div>
        </section>

        <TabsBlock :tabs="tabs" v-model="activeTab">
          <template #students>
            <div class="term-details__panel-header">
              <LineTitleBlock title="لیست طلبه‌های این ترم" title-en="Seminarians List" />
              <BaseButton
                text="افزودن طلبه"
                custom-class="term-details__panel-btn"
                @click="onOpenAddStudent"
              >
                <template #appendIcon>
                  <SvgIcon name="arrow-left" :size="16" color="#fff" />
                </template>
              </BaseButton>
            </div>

            <SkeletonLoaderBlock v-if="studentsPending" :rows="4" :cols-per-row="1" />
            <div v-else-if="students.length > 0">
              <div v-for="student in students" :key="student.id" class="term-details__student-row">
                <div class="term-details__student-main">
                  <div v-if="studentAvatar(student?.user)" class="term-details__avatar">
                    <img :src="studentAvatar(student?.user)" :alt="student.name" />
                  </div>
                  <div v-else class="term-details__avatar term-details__avatar--placeholder">
                    <SvgIcon name="user" :size="20" color="#bcbcbc" />
                  </div>
                  <div>
                    <p class="term-details__student-name">{{ student?.user?.name || '—' }}</p>
                    <p class="term-details__student-meta">
                      <span dir="ltr">{{ student?.user.phone || '—' }}</span>
                      <template v-if="student?.user.email">
                        <span class="term-details__sep">،</span>
                        <span dir="ltr">{{ student?.user.email }}</span>
                      </template>
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <NoItems v-else title="متاسفیم" desc="طلبه‌ای برای نمایش وجود ندارد." />

            <PaginationBlock :pagination="studentPaginationMeta" @update:page="setStudentPage" />
          </template>

          <template #courses>
            <div class="term-details__panel-header">
              <LineTitleBlock title="لیست دوره‌های این ترم" title-en="Courses List" />
              <BaseButton
                text="افزودن دوره"
                custom-class="term-details__panel-btn"
                @click="onOpenAddCourse"
              >
                <template #appendIcon>
                  <SvgIcon name="arrow-left" :size="16" color="#fff" />
                </template>
              </BaseButton>
            </div>

            <SkeletonLoaderBlock v-if="coursesPending" :rows="4" :cols-per-row="1" />
            <div v-else-if="termCourses.length > 0">
              <CourseItem
                v-for="course in termCourses"
                :key="course.id"
                :course="course"
                @delete="(course) => onAskDeleteCourse(course)"
              />
            </div>
            <NoItems v-else title="متاسفیم" desc="دوره‌ای برای نمایش وجود ندارد." />

            <PaginationBlock :pagination="coursePaginationMeta" @update:page="setCoursePage" />
          </template>
        </TabsBlock>

        <div class="term-details__divider" />

        <div class="term-details__footer">
          <BaseButton text="بستن" custom-class="term-details__close-btn" @click="close">
            <template #appendIcon>
              <SvgIcon name="arrow-left" :size="18" color="#fff" />
            </template>
          </BaseButton>
        </div>
      </div>
    </template>
  </BasicModal>
</template>

<script setup>
import { computed, ref } from 'vue'
import CourseItem from '../CourseItem.vue'
import useModal from '@/composables/useModal'
import { useQueryClient } from '@tanstack/vue-query'
import BasicModal from '@/components/BasicModal.vue'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { formatJalaaliDate } from '@/utils/date-utils'
import TabsBlock from '@/components/blocks/TabsBlock.vue'
import { usePagination } from '@/composables/usePagination'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import LineInfoBlock from '@/components/blocks/LineInfoBlock.vue'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import { useAdminTermEnrolleesQuery, useAdminTermQuery } from '@/services/query/admin-terms'
import {
  adminCoursesKeys,
  useAdminCoursesListQuery,
  useUpdateAdminCourseMutation,
} from '@/services/query/admin-courses'

defineOptions({ name: 'TermDetailsModal' })

const queryClient = useQueryClient()
const { openModal, getModal } = useModal()

const modalData = computed(() => getModal('TermDetailsModal')?.data ?? {})
const termId = computed(() => modalData.value.id ?? null)

const { data: term } = useAdminTermQuery(termId, {
  enabled: () => !!termId.value,
})

const tabs = [
  { name: 'courses', label: 'دوره‌ها', icon: 'list-bullets' },
  { name: 'students', label: 'طلبه‌ها', icon: 'users' },
]
const activeTab = ref('courses')

const studentFilters = ref({})
const {
  pagination: studentPagination,
  setPage: setStudentPage,
  reset: resetStudentPagination,
} = usePagination({ page: 1, perPage: 10 })

const { data: studentsData, isLoading: studentsPending } = useAdminTermEnrolleesQuery(
  termId,
  studentFilters,
  studentPagination,
  {
    enabled: () => !!termId.value && activeTab.value === 'students',
    keepPreviousData: true,
  }
)

const students = computed(() => studentsData.value?.data ?? [])
const studentPaginationMeta = computed(() => ({
  page: studentPagination.value.page,
  perPage: studentPagination.value.perPage,
  ...studentsData.value?.meta,
}))

const studentAvatar = (student) => student.avatarUrl || student.avatarDownloadUrl || ''

const courseFilters = computed(() => ({ termId: termId.value }))
const { pagination: coursePagination, setPage: setCoursePage } = usePagination({
  page: 1,
  perPage: 10,
})

const { data: coursesData, isLoading: coursesPending } = useAdminCoursesListQuery(
  courseFilters,
  coursePagination,
  {
    enabled: () => !!termId.value && activeTab.value === 'courses',
    keepPreviousData: true,
  }
)

const termCourses = computed(() => coursesData.value?.data ?? [])
const coursePaginationMeta = computed(() => ({
  page: coursePagination.value.page,
  perPage: coursePagination.value.perPage,
  ...coursesData.value?.meta,
}))

const invalidateCourses = () => queryClient.invalidateQueries({ queryKey: adminCoursesKeys.all })

// Backend has no dedicated status endpoint — PATCH /courses/:id with { isActive }.
const updateCourseMutation = useUpdateAdminCourseMutation()

const onOpenAddCourse = () => {
  openModal('AttachCourseToTermModal', { termId: termId.value })
}

const onAskDeleteCourse = (course) => {
  updateCourseMutation.mutate(
    { id: course.id, payload: { termId: null } },
    { onSuccess: invalidateCourses }
  )
}

const onOpenAddStudent = () => {
  openModal('AddTermStudentModal', { termId: termId.value })
  resetStudentPagination()
}
</script>

<style lang="scss" scoped>
.term-details {
  width: 100%;
  text-align: start;

  &__loading {
    text-align: center;
    padding: 2rem;
    color: var(--color-prim-gray);
  }

  &__section {
    margin-bottom: 1.5rem;
  }

  &__overview {
    display: flex;
    gap: 1rem;
    align-items: flex-start;

    @media (max-width: 768px) {
      flex-direction: column;
    }
  }

  &__image {
    width: 5rem;
    height: 5rem;
    border-radius: 0.5rem;
    background: #f5f5f5;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  &__overview-grid {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.25rem;

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

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

  &__cell--full {
    grid-column: 1 / -1;
  }

  &__panel-header {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    margin-bottom: 0.5rem;
  }

  &__panel-btn {
    min-width: 11rem;
    padding: 0 1rem;
    margin-inline-start: auto;
  }

  &__placeholder {
    text-align: center;
    color: var(--color-prim-gray);
    padding: 2rem;
  }

  &__student-row {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.625rem 0.875rem;
    background: rgba(255, 255, 255, 85%);
    border-radius: 0.875rem;
    box-shadow: 0 4px 10px -6px rgba(241, 241, 241, 70%);
    margin-bottom: 0.5rem;
  }

  &__student-main {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    flex: 1;
    min-width: 0;
  }

  &__avatar {
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 9999px;
    overflow: hidden;
    border: 1px solid #eee;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    &--placeholder {
      background: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      border: none;
    }
  }

  &__student-name {
    font-family: var(--font-family-fa);
    font-size: 0.95rem;
    color: #4b4b4b;
    margin: 0 0 0.25rem;
  }

  &__student-meta {
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
    font-weight: 300;
    color: #848484;
    margin: 0;
  }

  &__sep {
    color: #c4c4c4;
    margin-inline: 0.25rem;
  }

  &__student-actions {
    display: flex;
    align-items: center;
    gap: 0.375rem;
  }

  &__divider {
    border-block-end: 1px solid var(--color-thd-gray);
    margin-block: 1.5rem;
  }

  &__footer {
    display: flex;
    justify-content: flex-end;
  }

  &__close-btn {
    min-width: 12rem;
  }
}
</style>
