<template>
  <BasicModal width="95%" max-width="80rem" min-width="auto" :show-close-button="true">
    <template #default="{ close }">
      <div class="course-details">
        <LineTitleBlock title="جزئیات دوره" title-en="details" />

        <SkeletonLoaderBlock v-if="isLoading" :rows="3" :cols-per-row="1" />

        <template v-else-if="course">
          <div class="course-details__hero">
            <div class="course-details__image">
              <img v-if="course.image" :src="course.image" :alt="course.title" />
              <SvgIcon v-else name="book" :size="32" color="#bcbcbc" />
            </div>
            <div class="course-details__grid">
              <LineInfoBlock title="عنوان دوره" :desc="course.title || '—'" />
              <LineInfoBlock
                title="تاریخ شروع"
                :numeric-desc="course.faStartDate || formatJalaaliDate(course.startDate) || '—'"
              />
              <LineInfoBlock
                title="تاریخ پایان"
                :numeric-desc="course.faEndDate || formatJalaaliDate(course.endDate) || '—'"
              />
              <LineInfoBlock title="تعداد جلسات" :numeric-desc="course.sessionsCount ?? 0" />
              <LineInfoBlock title="پیش‌نیاز دوره" :desc="teacherName" />
            </div>
          </div>

          <div v-if="course.description" class="course-details__description">
            <LineInfoBlock title="توضیحات دوره" :desc="course.description" />
          </div>
        </template>

        <NoItems v-else title="یافت نشد" desc="اطلاعات این دوره در دسترس نیست." />

        <TabsBlock v-if="course" :tabs="tabs" v-model="activeTab">
          <template #sessions>
            <div class="course-details__panel-header">
              <LineTitleBlock title="لیست جلسات" title-en="Sessions" />
              <BaseButton
                text="افزودن جلسه به این دوره"
                custom-class="course-details__panel-btn"
                @click="onOpenAddSession"
              >
                <template #appendIcon>
                  <SvgIcon name="arrow-left" :size="16" color="#fff" />
                </template>
              </BaseButton>
            </div>

            <SkeletonLoaderBlock v-if="sessionsPending" :rows="4" :cols-per-row="1" />
            <div v-else-if="sessions.length > 0">
              <CourseSessionItem v-for="session in sessions" :key="session.id" :session="session" />
            </div>
            <NoItems v-else title="بدون جلسه" desc="جلسه‌ای برای این دوره ثبت نشده است." />

            <PaginationBlock
              v-if="sessionsPaginationMeta.lastPage > 1"
              :pagination="sessionsPaginationMeta"
              @update:page="setSessionsPage"
            />
          </template>

          <template #students>
            <div class="course-details__panel-header">
              <LineTitleBlock title="دانشجویان" title-en="Students" />
              <BaseButton
                text="افزودن دانشجو به این دوره"
                custom-class="course-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="course-details__student-row"
              >
                <div class="course-details__student-main">
                  <div v-if="student.avatarUrl" class="course-details__avatar">
                    <img :src="student.avatarUrl" :alt="studentName(student)" />
                  </div>
                  <div v-else class="course-details__avatar course-details__avatar--placeholder">
                    <SvgIcon name="user" :size="20" color="#bcbcbc" />
                  </div>
                  <div>
                    <p class="course-details__student-name">{{ studentName(student) }}</p>
                    <p class="course-details__student-meta">
                      <span>{{ student.address?.province?.name || '—' }}</span>
                      <span class="course-details__sep">،</span>
                      <span>{{ student.address?.city?.name || '—' }}</span>
                    </p>
                  </div>
                </div>
                <div class="course-details__student-actions">
                  <CircleButton
                    v-if="student.phoneNumber"
                    tooltip="ارسال پیام"
                    bg-color="rgba(104, 104, 104, 0.05)"
                    size="2.25rem"
                    @click="onMessageStudent(student)"
                  >
                    <template #icon>
                      <SvgIcon name="chat" :size="16" color="var(--color-sec-gray)" />
                    </template>
                  </CircleButton>
                  <CircleButton
                    tooltip="حذف"
                    bg-color="rgba(104, 104, 104, 0.05)"
                    size="2.25rem"
                    @click="onAskRemoveStudent(student)"
                  >
                    <template #icon>
                      <SvgIcon name="trash" :size="16" color="var(--color-error)" />
                    </template>
                  </CircleButton>
                </div>
              </div>
            </div>
            <NoItems v-else title="بدون دانشجو" desc="دانشجویی به این دوره اضافه نشده است." />

            <PaginationBlock
              v-if="studentsPaginationMeta.lastPage > 1"
              :pagination="studentsPaginationMeta"
              @update:page="setStudentsPage"
            />
          </template>
        </TabsBlock>

        <div class="course-details__divider" />

        <div class="course-details__footer">
          <BaseButton text="تایید" custom-class="course-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 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 CircleButton from '@/components/CircleButton.vue'
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 CourseSessionItem from '@/features/admin/courses/components/CourseSessionItem.vue'
import {
  adminCoursesKeys,
  useAdminCourseQuery,
  useAdminCourseSessionsQuery,
  useAdminCourseStudentsQuery,
  useRemoveAdminCourseStudentMutation,
} from '@/services/query/admin-courses'

defineOptions({ name: 'CourseDetailsModal' })

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

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

const { data: course, isLoading } = useAdminCourseQuery(courseId, {
  enabled: () => !!courseId.value,
})

const teacherName = computed(() => {
  const t = course.value?.teacher
  if (!t) return '—'
  return `${t.firstName || ''} ${t.lastName || ''}`.trim() || t.fullName || '—'
})

const tabs = [
  { name: 'sessions', label: 'لیست جلسات', icon: 'list-bullets' },
  { name: 'students', label: 'دانشجویان', icon: 'users' },
]
const activeTab = ref('sessions')

const sessionsFilters = ref({})
const { pagination: sessionsPagination, setPage: setSessionsPage } = usePagination({
  page: 1,
  perPage: 10,
})

const { data: sessionsData, isLoading: sessionsPending } = useAdminCourseSessionsQuery(
  courseId,
  sessionsFilters,
  sessionsPagination,
  {
    enabled: () => !!courseId.value && activeTab.value === 'sessions',
    keepPreviousData: true,
  }
)

const sessions = computed(() => sessionsData.value?.data ?? [])
const sessionsPaginationMeta = computed(() => ({
  page: sessionsPagination.value.page,
  perPage: sessionsPagination.value.perPage,
  ...sessionsData.value?.meta,
}))

const studentsFilters = ref({})
const { pagination: studentsPagination, setPage: setStudentsPage } = usePagination({
  page: 1,
  perPage: 10,
})

const { data: studentsData, isLoading: studentsPending } = useAdminCourseStudentsQuery(
  courseId,
  studentsFilters,
  studentsPagination,
  {
    enabled: () => !!courseId.value && activeTab.value === 'students',
    keepPreviousData: true,
  }
)

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

const studentName = (student) =>
  `${student.firstName || ''} ${student.lastName || ''}`.trim() ||
  student.fullName ||
  student.phoneNumber ||
  '—'

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

const removeStudentMutation = useRemoveAdminCourseStudentMutation()

const onOpenAddSession = () => {
  openModal('AddSessionToCourseModal', { courseId: courseId.value })
}

const onOpenAddStudent = () => {
  openModal('AddCourseStudentModal', { courseId: courseId.value })
}

const onAskRemoveStudent = (student) => {
  openModal('ConfirmModal', {
    title: `حذف ${studentName(student)}`,
    message: `آیا از حذف <strong>${studentName(student)}</strong> از این دوره اطمینان دارید؟`,
    onConfirm: () =>
      removeStudentMutation.mutate(
        { courseId: courseId.value, userId: student.id },
        { onSuccess: invalidate }
      ),
  })
}

const onMessageStudent = (student) => {
  if (!student?.phoneNumber) return
  window.location.href = `sms:${student.phoneNumber}`
}
</script>

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

  &__hero {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    margin: 1rem 0 0.5rem;

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

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

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

  &__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(5, 1fr);
    }
  }

  &__description {
    margin-block: 0.5rem 1rem;
  }

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

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

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