<template>
  <BasicModal
    title="حضور و غیاب"
    title-en="Attendance"
    width="95%"
    max-width="60rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div class="session-attendance">
        <div class="session-attendance__filters">
          <SelectField
            v-model="filters.termId"
            name="termId"
            label="ترم"
            :options="termOptions"
            option-label="title"
            option-value="id"
            :searchable="true"
            :on-search="searchTerms"
          />
          <SelectField
            v-model="filters.courseId"
            name="courseId"
            label="دوره"
            :options="courseOptions"
            option-label="title"
            option-value="id"
            :disabled="!filters.termId"
          />
        </div>

        <SkeletonLoaderBlock v-if="isLoading" :rows="4" :cols-per-row="1" />
        <div v-else-if="attendance.length > 0" class="session-attendance__list">
          <div v-for="row in attendance" :key="rowKey(row)" class="session-attendance__row">
            <div class="session-attendance__user">
              <div v-if="row.user?.avatarUrl" class="session-attendance__avatar">
                <img :src="row.user.avatarUrl" :alt="userName(row.user)" />
              </div>
              <div
                v-else
                class="session-attendance__avatar session-attendance__avatar--placeholder"
              >
                <SvgIcon name="user" :size="20" color="#bcbcbc" />
              </div>
              <div>
                <p class="session-attendance__name">{{ userName(row.user) }}</p>
                <p class="session-attendance__meta">
                  <span>{{ row.user?.address?.province?.name || '—' }}</span>
                  <span class="session-attendance__sep">،</span>
                  <span>{{ row.user?.address?.city?.name || '—' }}</span>
                </p>
              </div>
            </div>
            <div
              class="session-attendance__status"
              :class="`session-attendance__status--${row.status || 'unknown'}`"
            >
              <span class="session-attendance__status-dot" />
              {{ statusLabel(row.status) }}
            </div>
          </div>
        </div>
        <NoItems v-else title="موردی یافت نشد" desc="لیست حضور و غیابی برای نمایش وجود ندارد." />

        <PaginationBlock :pagination="paginationMeta" @update:page="setPage" />

        <div class="session-attendance__divider" />

        <div class="session-attendance__footer">
          <BaseButton text="بستن" custom-class="session-attendance__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, watch } from 'vue'
import useModal from '@/composables/useModal'
import useDebounce from '@/composables/useDebounce'
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 SelectField from '@/components/form/SelectField.vue'
import { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import { useAdminTermsListQuery } from '@/services/query/admin-terms'
import { useAdminCoursesListQuery } from '@/services/query/admin-courses'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import { useAdminSessionAttendanceQuery } from '@/services/query/admin-sessions'

defineOptions({ name: 'SessionAttendanceModal' })

const { getModal } = useModal()

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

const filters = ref({ termId: '', courseId: '' })
const filtersRef = computed(() => ({
  termId: filters.value.termId,
  courseId: filters.value.courseId,
}))
const { pagination, setPage } = usePagination({ page: 1, perPage: 10 })

const { data, isLoading } = useAdminSessionAttendanceQuery(sessionId, filtersRef, pagination, {
  enabled: () => !!sessionId.value,
  keepPreviousData: true,
})

const attendance = computed(() => data.value?.data ?? [])
const paginationMeta = computed(() => ({
  page: pagination.value.page,
  perPage: pagination.value.perPage,
  ...data.value?.meta,
}))

const termSearch = ref('')
const termListFilters = computed(() => ({ title: termSearch.value }))
const termPagination = ref({ page: 1, perPage: 10 })
const { data: termsResponse } = useAdminTermsListQuery(termListFilters, termPagination)
const termOptions = computed(() => termsResponse.value?.data ?? [])

const courseListFilters = computed(() => ({ termId: filters.value.termId }))
const coursePagination = ref({ page: 1, perPage: 50 })
const { data: coursesResponse } = useAdminCoursesListQuery(courseListFilters, coursePagination, {
  enabled: () => !!filters.value.termId,
})
const courseOptions = computed(() => coursesResponse.value?.data ?? [])

const searchTerms = useDebounce((q) => {
  termSearch.value = q || ''
}, 400)

watch(
  () => filters.value.termId,
  () => {
    filters.value.courseId = ''
  }
)

const userName = (user) =>
  `${user?.firstName || ''} ${user?.lastName || ''}`.trim() || user?.fullName || '—'

const rowKey = (row) => row.id || `${row.userId}-${row.sessionId}`

const statusLabel = (status) => {
  if (status === 'present') return 'حاضر'
  if (status === 'absent') return 'غایب'
  if (status === 'late') return 'با تاخیر'
  if (status === 'leave') return 'مرخصی'
  return 'نامشخص'
}
</script>

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

  &__filters {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.5rem;
    margin-block: 0.75rem;

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

  &__list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  &__row {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    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%);
  }

  &__user {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 0.625rem;
    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;
    }
  }

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

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

  &__status {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    padding: 0.25rem 0.875rem;
    border-radius: 0.875rem;
    font-family: var(--font-family-fa);
    font-size: 0.75rem;

    &--present {
      background: rgba(0, 154, 18, 8%);
      color: #009a12;
    }

    &--absent {
      background: rgba(204, 40, 49, 8%);
      color: var(--color-error);
    }

    &--late {
      background: rgba(255, 165, 0, 8%);
      color: #cc6f00;
    }

    &--leave {
      background: rgba(104, 104, 104, 8%);
      color: #686868;
    }

    &--unknown {
      background: rgba(180, 180, 180, 10%);
      color: #848484;
    }
  }

  &__status-dot {
    width: 0.375rem;
    height: 0.375rem;
    border-radius: 9999px;
    background: currentcolor;
  }

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

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

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