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

    <form class="term-form__form" @submit.prevent="onSubmit">
      <div class="term-form__grid">
        <div class="term-form__main-col">
          <LineTitleBlock title="اطلاعات ترم" title-en="Term Details" />
          <div class="term-form__row">
            <div class="term-form__cell term-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="term-form__cell term-form__cell--third">
              <TextField
                v-model="form.minimumScore"
                name="minimumScore"
                label="حد نصاب قبولی"
                inputmode="numeric"
                :convert-digits="true"
                :error="errors.minimumScore"
                @blur="validateAt('minimumScore', form.minimumScore)"
              />
            </div>
            <div class="term-form__cell term-form__cell--third">
              <TextField
                v-model="form.score"
                name="score"
                label="کل نمره آزمون"
                inputmode="numeric"
                :convert-digits="true"
                :error="errors.score"
                @blur="validateAt('score', form.score)"
              />
            </div>
            <div class="term-form__cell term-form__cell--full">
              <TextareaField
                v-model="form.description"
                name="description"
                label="توضیحات"
                :row="5"
                :error="errors.description"
              />
            </div>
          </div>
        </div>

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

      <div class="term-form__divider" />

      <div class="term-form__actions">
        <BaseButton
          variant="transparent"
          text="منصرف شدم"
          custom-class="term-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="term-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 { 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 { termSchema } from '@/features/admin/terms/schema'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import ImageCropper from '@/components/form/ImageCropper.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import { useUploadMediaMutation } from '@/services/query/auth'
import TextareaField from '@/components/form/TextareaField.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import {
  adminTermsKeys,
  useAddAdminTermMutation,
  useAdminTermQuery,
  useUpdateAdminTermMutation,
} from '@/services/query/admin-terms'

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

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

const form = ref({
  title: '',
  description: '',
  isActive: true,
  minimumScore: '',
  score: '',
  coverMediaId: null,
})

const image = ref(null)

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

const { data: existingTerm } = useAdminTermQuery(termId, {
  enabled: () => !!termId.value,
})

watch(
  existingTerm,
  (term) => {
    if (!term) return
    form.value = {
      title: term.title || '',
      description: term.description || '',
      isActive: term.isActive ?? true,
      minimumScore: term.minimumScore ?? '',
      score: term.score ?? '',
    }
    if (term.coverUrl) image.value = { url: term.coverUrl }
  },
  { immediate: true }
)

const uploadMutation = useUploadMediaMutation()

const onImageCropped = async (file) => {
  try {
    const formData = objectToFormData({ file, purpose: 'cover', context: 'term' })
    const response = await uploadMutation.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 = useAddAdminTermMutation()
const updateMutation = useUpdateAdminTermMutation()

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

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  if (isEditMode.value) {
    await updateMutation.mutateAsync({ id: termId.value, payload })
  } else {
    await addMutation.mutateAsync(payload)
  }
  await queryClient.resetQueries({ queryKey: adminTermsKeys.all })
  router.push({ name: 'admin-terms' })
}

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

<style lang="scss" scoped>
.term-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%;
    }
  }

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

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

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

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