<template>
  <div class="exam-form">
    <BoxedIconTitleBlock
      class="exam-form__heading"
      :title="isEditMode ? 'ویرایش آزمون' : 'طراحی سوال'"
      desc="در این قسمت شما می‌توانید سوالات خود را ایجاد، حذف، ویرایش کنید"
    >
      <template #icon>
        <SvgIcon name="pencil" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <form class="exam-form__form" @submit.prevent="onSubmit">
      <div class="exam-form__card">
        <div class="exam-form__grid">
          <SelectField
            v-model="form.sessionId"
            name="sessionId"
            label="جلسه"
            :options="sessionOptions"
            option-label="title"
            option-value="id"
            :searchable="true"
            :on-search="searchSessions"
            :error="errors.sessionId"
          />
          <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>
          <TextField
            v-model="form.minimumScore"
            name="minimumScore"
            label="حد نصاب قبولی"
            inputmode="numeric"
            :convert-digits="true"
            :error="errors.minimumScore"
            @blur="validateAt('minimumScore', form.minimumScore)"
          >
            <template #appendIcon>
              <SvgIcon name="newspaper" :size="20" color="var(--color-thd-gray)" />
            </template>
          </TextField>
          <TextField
            v-model="form.score"
            name="score"
            label="کل نمره آزمون"
            inputmode="numeric"
            :convert-digits="true"
            :error="errors.score"
            @blur="validateAt('score', form.score)"
          >
            <template #appendIcon>
              <SvgIcon name="newspaper" :size="20" color="var(--color-thd-gray)" />
            </template>
          </TextField>
          <TextField
            v-model="form.durationMinutes"
            name="durationMinutes"
            label="مدت زمان (دقیقه)"
            inputmode="numeric"
            :convert-digits="true"
            :error="errors.durationMinutes"
            @blur="validateAt('durationMinutes', form.durationMinutes)"
          >
            <template #appendIcon>
              <SvgIcon name="clock" :size="20" color="var(--color-thd-gray)" />
            </template>
          </TextField>
          <div class="exam-form__toggle-cell">
            <ToggleSwitch v-model="form.isRandom" label="به صــــورت رندوم باشد." />
          </div>
        </div>
        <TextareaField
          v-model="form.description"
          name="description"
          label="توضیحات آزمون"
          :row="4"
        />
      </div>

      <div>
        <ExamQuestionBuilder v-model="questions" :disabled="submitting" />
        <p v-if="questionError" class="exam-form__error">{{ questionError }}</p>
      </div>

      <div class="exam-form__divider" />

      <div class="exam-form__actions">
        <BaseButton
          variant="transparent"
          text="منصرف شدم"
          custom-class="exam-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="exam-form__btn-submit"
        >
          <template #appendIcon>
            <SvgIcon name="arrow-left" :size="20" color="#fff" />
          </template>
        </BaseButton>
      </div>
    </form>
  </div>
</template>

<script setup>
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 { examSchema } from '@/features/admin/exams/schema'
import SelectField from '@/components/form/SelectField.vue'
import ToggleSwitch from '@/components/form/ToggleSwitch.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import { useAdminSessionsListQuery } from '@/services/query/admin-sessions'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import ExamQuestionBuilder from '@/features/admin/exams/components/ExamQuestionBuilder.vue'
import {
  adminExamsKeys,
  useAddAdminExamMutation,
  useAddAdminExamQuestionMutation,
  useAdminExamQuery,
  useUpdateAdminExamMutation,
} from '@/services/query/admin-exams'

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

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

const form = ref({
  title: '',
  sessionId: '',
  minimumScore: '',
  score: '',
  durationMinutes: '',
  isRandom: true,
  description: '',
})

const createId = (prefix) => `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`

const blankOption = () => ({ id: createId('option'), optionText: '', isCorrect: false })

const blankQuestion = () => ({
  id: createId('question'),
  questionText: '',
  score: '',
  options: [blankOption(), { ...blankOption(), id: createId('option') }],
  __local: true,
})

const questions = ref([blankQuestion()])
const questionError = ref('')

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

const sessionSearch = ref('')
const sessionFilters = computed(() => ({ search: sessionSearch.value }))
const sessionPagination = ref({ page: 1, perPage: 10 })
const { data: sessionsResponse } = useAdminSessionsListQuery(sessionFilters, sessionPagination)
const selectedSession = ref(null)
const sessionOptions = computed(() => {
  const base = sessionsResponse.value?.data ?? []
  if (selectedSession.value && !base.some((s) => s.id === selectedSession.value.id)) {
    return [...base, selectedSession.value]
  }
  return base
})

const searchSessions = useDebounce((q) => {
  sessionSearch.value = q || ''
}, 400)

const { data: existingExam } = useAdminExamQuery(examId, {
  enabled: () => !!examId.value,
})

const normalizeExistingQuestions = (raw = []) => {
  if (!Array.isArray(raw) || raw.length === 0) return [blankQuestion()]
  return raw.map((q, qIdx) => {
    const options = Array.isArray(q.options) ? q.options : []
    return {
      id: q.id ?? createId(`question-${qIdx}`),
      questionText: q.questionText || '',
      score: q.score ?? '',
      options: options.map((o, oIdx) => ({
        id: o.id ?? createId(`option-${qIdx}-${oIdx}`),
        optionText: o.optionText || '',
        isCorrect: !!o.isCorrect,
      })),
    }
  })
}

watch(
  existingExam,
  (exam) => {
    if (!exam) return
    if (exam.session) selectedSession.value = exam.session
    form.value = {
      title: exam.title || '',
      sessionId: exam.session?.id || exam.sessionId || '',
      minimumScore: exam.minimumScore ?? exam.passScore ?? '',
      score: exam.score ?? '',
      durationMinutes: exam.durationMinutes ?? '',
      isRandom: exam.isRandom ?? true,
      description: exam.description || '',
    }
    questions.value = normalizeExistingQuestions(exam.questions)
  },
  { immediate: true }
)

const validateLocalQuestions = () => {
  const localOnes = questions.value.filter((q) => q.__local === true)
  if (!isEditMode.value && localOnes.length === 0) {
    questionError.value = 'حداقل یک سوال اضافه کنید.'
    return null
  }
  for (const q of localOnes) {
    if (!String(q.questionText || '').trim()) {
      questionError.value = 'متن همه سوالات را وارد کنید.'
      return null
    }
    const validOptions = q.options.filter((o) => String(o.optionText || '').trim())
    if (validOptions.length < 2) {
      questionError.value = 'برای هر سوال حداقل دو گزینه وارد کنید.'
      return null
    }
    if (!validOptions.some((o) => o.isCorrect)) {
      questionError.value = 'گزینه صحیح هر سوال را انتخاب کنید.'
      return null
    }
  }
  questionError.value = ''
  return localOnes.map((q, idx) => ({
    questionText: q.questionText.trim(),
    position: idx + 1,
    score: Number(q.score) || 0,
    options: q.options
      .filter((o) => String(o.optionText || '').trim())
      .map((o) => ({
        optionText: o.optionText.trim(),
        isCorrect: !!o.isCorrect,
      })),
  }))
}

const buildExamPayload = (values) => ({
  sessionId: values.sessionId,
  title: values.title,
  description: values.description,
  minimumScore: Number(values.minimumScore) || 0,
  score: Number(values.score) || 0,
  durationMinutes: Number(values.durationMinutes) || 0,
  isRandom: values.isRandom,
})

const addExamMutation = useAddAdminExamMutation()
const updateExamMutation = useUpdateAdminExamMutation()
const addQuestionMutation = useAddAdminExamQuestionMutation()

const submitting = computed(
  () =>
    addExamMutation.isPending.value ||
    updateExamMutation.isPending.value ||
    addQuestionMutation.isPending.value
)

const postQuestionsSequentially = async (id, list) => {
  for (const payload of list) {
    // eslint-disable-next-line no-await-in-loop
    await addQuestionMutation.mutateAsync({ examId: id, payload })
  }
}

const onSubmit = async () => {
  const { isValid } = await validate(form.value)
  const newQuestions = validateLocalQuestions()
  if (!isValid || !newQuestions) return

  const examPayload = buildExamPayload(form.value)
  let targetExamId = examId.value
  if (isEditMode.value) {
    await updateExamMutation.mutateAsync({ id: targetExamId, payload: examPayload })
  } else {
    const created = await addExamMutation.mutateAsync(examPayload)
    targetExamId = created?.data?.id ?? created?.id ?? targetExamId
  }
  if (targetExamId && newQuestions.length > 0) {
    await postQuestionsSequentially(targetExamId, newQuestions)
  }
  await queryClient.invalidateQueries({ queryKey: adminExamsKeys.all, refetchType: 'all' })
  router.push({ name: 'admin-exams' })
}

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

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

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  &__card {
    border-radius: 1.5rem;
    padding: 1rem;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 2.5%);
  }

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

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

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

  &__toggle-cell {
    display: flex;
    align-items: flex-end;
    min-height: 4.25rem;
    margin-right: 40px;
    margin-top: 10px;

    > div {
      height: 100%;
      display: flex;
      align-items: center;
    }
  }

  &__error {
    margin-top: 0.5rem;
    padding-inline: 0.5rem;
    color: var(--color-error);
    font-family: var(--font-family-fa);
    font-size: 0.75rem;
  }

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

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

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

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