<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__image-col">
          <ImageCropper
            v-model="image"
            name="image"
            bg-color="#eeeeee"
            @crop="onImageCropped"
            @error="onImageError"
          />
        </div>

        <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">
              <DatePickerField
                v-model="form.startDate"
                name="startDate"
                label="تاریخ شروع"
                :min="todayIso"
                :error="errors.startDate"
              />
            </div>
            <div class="term-form__cell term-form__cell--third">
              <DatePickerField
                v-model="form.endDate"
                name="endDate"
                label="تاریخ پایان"
                :min="todayIso"
                :error="errors.endDate"
              />
            </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>

      <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 { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue3-toastify'
import { useQueryClient } from '@tanstack/vue-query'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import BaseButton from '@/components/BaseButton.vue'
import TextField from '@/components/form/TextField.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import DatePickerField from '@/components/form/DatePickerField.vue'
import ImageCropper from '@/components/form/ImageCropper.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import useYup from '@/composables/useYup'
import {
  adminTermsKeys,
  useAddAdminTermMutation,
  useAdminTermQuery,
  useUpdateAdminTermMutation,
} from '@/services/query/admin-terms'
import { useUploadTemporaryMutation } from '@/services/query/auth'
import { termSchema } from '@/features/admin/terms/schema'
import { objectToFormData } from '@/utils/object-to-formdata'

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 todayIso = new Date().toISOString()

const form = ref({
  title: '',
  startDate: '',
  endDate: '',
  description: '',
  imageId: null,
})

const image = ref(null)

const schema = termSchema

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

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

watch(existingTerm, (term) => {
  if (!term) return
  form.value = {
    title: term.title || '',
    startDate: term.startDate || '',
    endDate: term.endDate || '',
    description: term.description || '',
    imageId: term.imageId || null,
  }
  if (term.image) image.value = { url: term.image }
})

const uploadMutation = useUploadTemporaryMutation()

const onImageCropped = async (file) => {
  try {
    const formData = objectToFormData({ file, subType: 'avatar', context: 'term' })
    const response = await uploadMutation.mutateAsync(formData)
    const payload = response?.data ?? response
    image.value = { url: payload?.url, uploadId: payload?.uploadId, ...payload }
    form.value.imageId = payload?.uploadId || 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.invalidateQueries({ 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: 4fr 8fr;
    }

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

  &__image-col {
    order: 2;

    @media (min-width: 1024px) {
      order: 1;
      padding: 0.5rem;
    }
  }

  &__main-col {
    order: 1;

    @media (min-width: 1024px) {
      order: 2;
      padding-inline-start: 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: flex-end;
    gap: 0.625rem;
  }

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

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