<template>
  <BasicModal
    title="افزودن دوره"
    title-en="Add Course"
    width="95%"
    max-width="42rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <div class="attach-course">
        <div class="attach-course__search">
          <SvgIcon name="book" :size="18" color="var(--color-thd-gray)" />
          <input
            v-model="searchQuery"
            type="text"
            class="attach-course__search-input"
            placeholder="عنوان دوره مورد نظر را جست‌وجو کنید"
            @input="onSearch"
          />
        </div>

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

        <div v-else-if="templates.length > 0" class="attach-course__list">
          <div v-for="template in templates" :key="template.id" class="attach-course__row">
            <div class="attach-course__main">
              <div class="attach-course__image">
                <img v-if="template.image" :src="template.image" :alt="template.title" />
                <SvgIcon v-else name="book" :size="20" color="#bcbcbc" />
              </div>
              <div class="attach-course__text">
                <p class="attach-course__title">{{ template.title }}</p>
                <p class="attach-course__teacher">
                  <SvgIcon name="user" :size="11" color="#bcbcbc" />
                  <span class="attach-course__teacher-label">استاد:</span>
                  <span class="attach-course__teacher-name">{{ teacherName(template) }}</span>
                </p>
              </div>
            </div>

            <CircleButton
              v-if="attachedCourseByTemplate(template.id)"
              tooltip="حذف از ترم"
              bg-color="rgba(104, 104, 104, 0.05)"
              size="2.25rem"
              type="button"
              :loading="pendingId === template.id"
              @click="onDetach(template)"
            >
              <template #icon>
                <SvgIcon name="trash" :size="16" color="var(--color-error)" />
              </template>
            </CircleButton>
            <CircleButton
              v-else
              tooltip="افزودن به ترم"
              bg-color="rgba(104, 104, 104, 0.05)"
              size="2.25rem"
              type="button"
              :loading="pendingId === template.id"
              @click="onAttach(template)"
            >
              <template #icon>
                <SvgIcon name="plus" :size="16" color="var(--color-sec-gray)" />
              </template>
            </CircleButton>
          </div>
        </div>

        <NoItems v-else title="بدون نتیجه" desc="دوره الگویی یافت نشد." />

        <div class="attach-course__divider" />

        <div class="attach-course__footer">
          <BaseButton text="تایید" custom-class="attach-course__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 { 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 CircleButton from '@/components/CircleButton.vue'
import { adminTermsKeys } from '@/services/query/admin-terms'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import {
  adminCoursesKeys,
  useAdminCoursesListQuery,
  useUpdateAdminCourseMutation,
} from '@/services/query/admin-courses'

// TODO: repurpose this modal as "copy course from another term" — the original
// flow (link a stand-alone template to a term) no longer matches the unified
// course model. Until then, this stays a stand-alone-course → new-offered-course copy.

defineOptions({ name: 'AttachCourseToTermModal' })

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

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

const searchQuery = ref('')
const templateFilters = computed(() => ({ title: searchQuery.value }))
const templatePagination = ref({ page: 1, perPage: 20 })

const { data: templatesResponse, isLoading } = useAdminCoursesListQuery(
  templateFilters,
  templatePagination
)

const templates = computed(() => templatesResponse.value?.data ?? [])

const courseFilters = computed(() => ({ termId: termId.value }))
const coursePagination = ref({ page: 1, perPage: 10 })
const { data: coursesResponse } = useAdminCoursesListQuery(courseFilters, coursePagination, {
  enabled: () => !!termId.value,
})

const attachedCourses = computed(() => coursesResponse.value?.data ?? [])

// Tracks which stand-alone course (termId=null) has already been copied
// into this term. We match by title since the unified model no longer
// keeps a back-reference to the source course.
const attachedCourseByTemplate = (sourceId) => {
  const source = templates.value.find((t) => t.id === sourceId)
  if (!source) return null
  return attachedCourses.value.find((c) => c.title === source.title)
}

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

const onSearch = useDebounce((event) => {
  searchQuery.value = event.target?.value || ''
  templatePagination.value = { ...templatePagination.value, page: 1 }
}, 400)

const pendingId = ref(null)

const updateMutation = useUpdateAdminCourseMutation()

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

const onAttach = async (template) => {
  if (!termId.value) return
  pendingId.value = template.id
  try {
    await updateMutation.mutateAsync({ id: template.id, payload: { termId: termId.value } })
    invalidate()
  } finally {
    pendingId.value = null
  }
}

const onDetach = async (template) => {
  const offered = attachedCourseByTemplate(template.id)
  if (!offered) return
  pendingId.value = template.id
  try {
    await updateMutation.mutateAsync({ id: template.id, payload: { termId: null } })
    invalidate()
  } finally {
    pendingId.value = null
  }
}

watch(termId, () => {
  searchQuery.value = ''
  pendingId.value = null
})
</script>

<style lang="scss" scoped>
.attach-course {
  width: 100%;
  text-align: start;
  padding: 0.5rem 0.25rem;

  &__search {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-block: 1rem;
    padding: 0 1rem;
    height: 2.75rem;
    border: 1px solid var(--color-thd-gray);
    border-radius: 9999px;
    background: #fff;
  }

  &__search-input {
    flex: 1;
    border: none;
    outline: none;
    background: transparent;
    font-family: var(--font-family-fa);
    font-size: 0.875rem;
    color: #4b4b4b;
    text-align: start;

    &::placeholder {
      color: var(--color-prim-gray);
    }
  }

  &__list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    max-height: 22rem;
    overflow-y: auto;
    padding-inline-end: 0.25rem;
  }

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

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

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

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

  &__text {
    min-width: 0;
  }

  &__title {
    font-family: var(--font-family-fa);
    font-size: 0.95rem;
    color: #4b4b4b;
    margin: 0 0 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__teacher {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
    color: #848484;
    margin: 0;
  }

  &__teacher-label {
    color: #b7b7b7;
  }

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

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

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