<template>
  <div class="course-form">
    <BoxedIconTitleBlock
      class="course-form__heading"
      :title="isEditMode ? 'ویرایش دوره' : 'افزودن دوره جدید'"
      :desc="
        isEditMode ? 'اطلاعات دوره را به‌روز کنید' : 'در این قسمت می‌توانید دوره جدید اضافه کنید'
      "
    >
      <template #icon>
        <SvgIcon name="book" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <form class="course-form__form" @submit.prevent="onSubmit">
      <div class="course-form__grid">
        <div class="course-form__main-col">
          <div class="course-form__row">
            <div class="course-form__cell course-form__cell--third">
              <TextField
                v-model="form.title"
                name="title"
                label="عنوان دوره"
                :error="errors.title"
                @blur="validateAt('title', form.title)"
              >
                <template #appendIcon>
                  <SvgIcon name="book" :size="20" color="var(--color-thd-gray)" />
                </template>
              </TextField>
            </div>
            <div class="course-form__cell course-form__cell--third">
              <SelectField
                v-model="form.teacherId"
                name="teacherId"
                label="استاد (اختیاری)"
                :options="teacherOptions"
                option-label="name"
                option-value="id"
                :searchable="true"
                :on-search="searchTeachers"
                :error="errors.teacherId"
              />
            </div>
            <div class="course-form__cell course-form__cell--third">
              <TextField
                v-model="form.capacity"
                name="capacity"
                label="ظرفیت (نفر)"
                inputmode="numeric"
                :convert-digits="true"
                :error="errors.capacity"
                @blur="validateAt('capacity', form.capacity)"
              />
            </div>
            <div class="course-form__cell course-form__cell--third">
              <SelectField
                v-model="form.termId"
                name="termId"
                label="ترم"
                :options="termOptions"
                option-label="title"
                option-value="id"
                :error="errors.termId"
              />
            </div>
            <div class="course-form__cell course-form__cell--third">
              <SelectField
                v-model="form.prerequisiteCourseIds"
                name="prerequisiteCourseIds"
                label="دوره‌های پیش‌نیاز"
                :options="prerequisiteOptions"
                option-label="title"
                option-value="id"
                :multiple="true"
                :searchable="true"
                :disabled="!form.termId"
                :on-search="searchPrerequisiteCourses"
              />
            </div>

            <div class="course-form__cell course-form__cell--full">
              <TextareaField
                v-model="form.description"
                name="description"
                label="توضیحات دوره"
                :row="5"
                :error="errors.description"
              />
            </div>
          </div>
        </div>

        <div class="course-form__image-col">
          <ImageCropper
            v-model="image"
            name="image"
            bg-color="#eeeeee"
            @crop="onImageCropped"
            @error="onImageError"
          />
        </div>
      </div>

      <div class="course-form__divider" />

      <div class="course-form__actions">
        <BaseButton
          variant="transparent"
          text="منصرف شدم"
          custom-class="course-form__btn-cancel"
          @click="onCancel"
        >
          <template #prependIcon>
            <SvgIcon name="caret-right" :size="14" color="var(--color-sec-gray)" />
          </template>
        </BaseButton>
        <BaseButton
          type="submit"
          :text="isEditMode ? 'ذخیره تغییرات' : 'تایید اطلاعات'"
          :loading="submitting"
          custom-class="course-form__btn-submit"
        >
          <template #appendIcon>
            <SvgIcon name="arrow-left" :size="20" color="#fff" />
          </template>
        </BaseButton>
      </div>
    </form>
  </div>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import useYup from '@/composables/useYup'
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useDebounce from '@/composables/useDebounce'
import { useQueryClient } from '@tanstack/vue-query'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import ImageCropper from '@/components/form/ImageCropper.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import { useUploadMediaMutation } from '@/services/query/auth'
import { courseSchema } from '@/features/admin/courses/schema'
import TextareaField from '@/components/form/TextareaField.vue'
import { useAdminUsersListQuery } from '@/services/query/admin-users'
import { useAdminTermsListQuery } from '@/services/query/admin-terms'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import {
  adminCoursesKeys,
  useAddAdminCourseMutation,
  useAdminCourseQuery,
  useAdminCoursesListQuery,
  useUpdateAdminCourseMutation,
} from '@/services/query/admin-courses'

const route = useRoute()
const router = useRouter()
const queryClient = useQueryClient()

const courseId = computed(() => (route.params.id ? Number(route.params.id) : null))
const termId = computed(() => (route.query.termId ? Number(route.query.termId) : null))
const isEditMode = computed(() => !!courseId.value)

const form = ref({
  title: '',
  teacherId: '',
  capacity: '',
  prerequisiteCourseIds: [],
  description: '',
  coverMediaId: null,
  termId: termId.value,
})

const image = ref(null)

const { validate, validateAt, errors } = useYup(courseSchema)

const teacherSearch = ref('')
const teacherFilters = computed(() => ({
  search: teacherSearch.value,
  roles: 'teacher',
}))
const teacherPagination = ref({ page: 1, perPage: 10 })
const { data: teachersResponse } = useAdminUsersListQuery(teacherFilters, teacherPagination)
const selectedTeacher = ref(null)
const teacherOptions = computed(() => {
  const base = teachersResponse.value?.data ?? []
  const merged =
    selectedTeacher.value && !base.some((t) => t.id === selectedTeacher.value.id)
      ? [...base, selectedTeacher.value]
      : base
  return merged.map((t) => ({
    ...t,
    label: `${t.firstName || ''} ${t.lastName || ''}`.trim() || t.fullName || '—',
  }))
})

const termFilters = ref({})
const termPagination = ref({ page: 1, perPage: 100 })
const { data: termsResponse } = useAdminTermsListQuery(termFilters, termPagination)
const termOptions = computed(() => termsResponse.value?.data ?? [])

const prereqSearch = ref('')
const prereqFilters = computed(() => ({ title: prereqSearch.value }))
const prereqPagination = ref({ page: 1, perPage: 10 })
const { data: prereqsResponse } = useAdminCoursesListQuery(prereqFilters, prereqPagination)
const selectedPrereqs = ref([])
const prerequisiteOptions = computed(() => {
  const base = prereqsResponse.value?.data ?? []
  const extras = selectedPrereqs.value.filter((p) => !base.some((b) => b.id === p.id))
  const merged = [...base, ...extras]
  return courseId.value ? merged.filter((c) => c.id !== courseId.value) : merged
})

const searchTeachers = useDebounce((q) => {
  teacherSearch.value = q || ''
}, 400)
const searchPrerequisiteCourses = useDebounce((q) => {
  prereqSearch.value = q || ''
}, 400)

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

watch(
  existingCourse,
  (course) => {
    if (!course) return
    const teacher = course.teacher
    if (teacher) selectedTeacher.value = teacher
    const prereqs = Array.isArray(course.prerequisiteCourseIds) ? course.prerequisiteCourseIds : []
    selectedPrereqs.value = prereqs.map((p) => p.course || p).filter((c) => c?.id)

    form.value = {
      title: course.title || '',
      teacherId: teacher?.id || course.teacherId || '',
      capacity: course.capacity ?? '',
      prerequisiteCourseIds: prereqs.map((p) => p.courseId ?? p.id).filter(Boolean),
      contentType: course.contentType || '',
      description: course.description || '',
      coverMediaId: course.coverMediaId || null,
      termId: course.termId ?? termId.value,
    }
    if (course.coverUrl) image.value = { url: course.coverUrl }
  },
  { immediate: true }
)

const coverUploadMutation = useUploadMediaMutation()

const onImageCropped = async (file) => {
  try {
    const formData = objectToFormData({ file, purpose: 'cover', context: 'course' })
    const response = await coverUploadMutation.mutateAsync(formData)
    const payload = response?.data ?? response
    image.value = { url: payload?.url, ...payload }
    form.value.coverMediaId = payload?.id
  } catch {
    /* handled globally */
  }
}

const onImageError = (msg) => toast.error(msg)

const addMutation = useAddAdminCourseMutation()
const updateMutation = useUpdateAdminCourseMutation()

const submitting = computed(
  () =>
    coverUploadMutation.isPending.value ||
    addMutation.isPending.value ||
    updateMutation.isPending.value
)

const onSubmit = async () => {
  if (coverUploadMutation.isPending.value) {
    toast.info('لطفاً تا پایان بارگذاری تصویر دوره منتظر بمانید.')
    return
  }
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  try {
    if (isEditMode.value) {
      await updateMutation.mutateAsync({ id: courseId.value, payload })
    } else {
      await addMutation.mutateAsync(payload)
    }
  } catch {
    return
  }
  await queryClient.invalidateQueries({ queryKey: adminCoursesKeys.all })
  router.push({ name: 'admin-courses' })
}

const onCancel = () => router.push({ name: 'admin-courses' })
</script>

<style lang="scss" scoped>
.course-form {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__form {
    background: rgba(255, 255, 255, 60%);
    padding: 1rem;
    border-radius: 1rem;
  }

  &__grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1rem;

    @media (min-width: 1024px) {
      grid-template-columns: 8fr 4fr;
    }

    @media (min-width: 1280px) {
      grid-template-columns: 9fr 3fr;
    }
  }

  &__image-col {
    @media (min-width: 1024px) {
      padding: 0.5rem;
    }
  }

  &__main-col {
    @media (min-width: 1024px) {
      padding-inline-end: 1.25rem;
    }
  }

  &__row {
    display: flex;
    flex-flow: column wrap;
    gap: 0.5rem;
    align-items: stretch;
    margin-bottom: 0.5rem;

    @media (min-width: 768px) {
      flex-direction: row;
    }
  }

  &__cell {
    width: 100%;

    &--third {
      @media (min-width: 768px) {
        width: 49%;
      }

      @media (min-width: 1280px) {
        width: 32.3%;
      }
    }

    &--full {
      width: 100%;
    }
  }

  &__uploader-label {
    display: block;
    margin-bottom: 0.5rem;
    font-family: var(--font-family-fa);
    font-weight: 300;
    line-height: 1.5rem;
    font-size: 0.875rem;
    color: var(--color-prim-gray);
  }

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

  &__actions {
    display: flex;
    justify-content: flex-end;
    justify-content: space-between;
    gap: 0.625rem;
  }

  &__btn-cancel {
    min-width: 9rem;
  }

  &__btn-submit {
    min-width: 12rem;
  }
}
</style>
