<template>
  <BasicModal
    :title="isEditMode ? 'ویرایش روایت' : 'ثبت روایت'"
    :title-en="isEditMode ? 'Edit Story' : 'Create Story'"
    width="95%"
    max-width="58rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <form class="create-narrative" @submit.prevent="onSubmit(close)">
        <div class="create-narrative__row create-narrative__row--two">
          <TextField
            v-model="form.title"
            name="title"
            label="عنوان روایت"
            :error="errors.title"
            @blur="validateAt('title', form.title)"
          >
            <template #appendIcon>
              <SvgIcon name="pencil" :size="20" color="var(--color-thd-gray)" />
            </template>
          </TextField>
          <SelectField
            v-model="form.missionaryRequestId"
            name="missionaryRequestId"
            label="درخواست مرتبط"
            placeholder="انتخاب کنید"
            :options="requestOptions"
            option-label="title"
            option-value="id"
          />
        </div>

        <div class="create-narrative__row">
          <TextareaField
            v-model="form.description"
            name="description"
            label="توضیحات روایت خود را وارد کنید"
            :row="4"
            :error="errors.description"
          />
        </div>

        <div class="create-narrative__upload">
          <FileUploader
            v-model="files"
            accept="image/*,video/mp4"
            :max-files="5"
            @select="onFilesSelect"
            @error="onFileError"
          />
        </div>

        <div class="create-narrative__divider" />

        <footer class="create-narrative__footer">
          <BaseButton
            type="submit"
            :text="isEditMode ? 'ذخیره تغییرات' : 'ثبت روایت'"
            custom-class="create-narrative__submit"
            :loading="createMutation.isPending.value || updateMutation.isPending.value"
            :disabled="uploadMutation.isPending.value"
          >
            <template #appendIcon>
              <SvgIcon name="arrow-left" :size="18" color="#fff" />
            </template>
          </BaseButton>
        </footer>
      </form>
    </template>
  </BasicModal>
</template>

<script setup>
import * as yup from 'yup'
import { computed, ref } from 'vue'
import { toast } from 'vue3-toastify'
import useYup from '@/composables/useYup'
import useModal from '@/composables/useModal'
import BasicModal from '@/components/BasicModal.vue'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import { useQueryClient } from '@tanstack/vue-query'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import FileUploader from '@/components/form/FileUploader.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import { useUploadMediaMutation } from '@/services/query/auth'
import TextareaField from '@/components/form/TextareaField.vue'
import { useMissionaryRequestsListQuery } from '@/services/query/missionary-requests'
import {
  missionaryMemoriesKeys,
  useCreateMissionaryMemoryMutation,
  useUpdateMissionaryMemoryMutation,
} from '@/services/query/missionary-memories'

defineOptions({ name: 'CreateNarrativeModal' })

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

const editingMemory = getModal('CreateNarrativeModal')?.data?.memory ?? null
const isEditMode = !!editingMemory

const form = ref({
  title: editingMemory?.title || '',
  description: editingMemory?.description || '',
  missionaryRequestId: editingMemory?.missionaryRequestId ?? null,
})

const files = ref(
  (editingMemory?.media ?? []).map((media) => ({
    id: media.id,
    name: media.fileName,
    size: media.fileSize,
    url: media.url,
    existing: true,
  }))
)

const schema = yup.object({
  title: yup.string().trim().required('عنوان روایت را وارد کنید'),
  description: yup.string().trim().notRequired(),
  missionaryRequestId: yup.mixed().nullable().notRequired(),
})

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

const requestsFilters = ref({ status: 'accepted' })
const requestsPagination = ref({ page: 1, perPage: 100 })
const { data: requestsData } = useMissionaryRequestsListQuery(requestsFilters, requestsPagination)

const requestOptions = computed(
  () => requestsData.value?.data?.items ?? requestsData.value?.data ?? []
)

const uploadMutation = useUploadMediaMutation()
const createMutation = useCreateMissionaryMemoryMutation()
const updateMutation = useUpdateMissionaryMemoryMutation()

const onFilesSelect = async (picked) => {
  for (const file of picked) {
    try {
      const fd = objectToFormData({ file, purpose: 'memory' })
      const response = await uploadMutation.mutateAsync(fd)
      const payload = response?.data ?? response
      const id = payload?.id ?? payload?.uploadId
      if (id == null) continue
      files.value = [
        ...files.value,
        { id, name: file.name, size: file.size, url: payload?.url ?? '' },
      ]
    } catch {
      toast.error(`بارگذاری فایل "${file.name}" با خطا مواجه شد.`)
    }
  }
}

const onFileError = (msg) => toast.warning(msg)

const onSubmit = async (close) => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return

  try {
    const body = {
      title: payload.title,
      description: payload.description,
      mediaIds: files.value
        .filter((f) => !f.existing)
        .map((f) => f.id)
        .filter((id) => id != null),
    }
    if (form.value.missionaryRequestId) body.missionaryRequestId = form.value.missionaryRequestId
    if (isEditMode) {
      await updateMutation.mutateAsync({ id: editingMemory.id, payload: body })
    } else {
      await createMutation.mutateAsync(body)
    }
    await queryClient.invalidateQueries({
      queryKey: missionaryMemoriesKeys.all,
      refetchType: 'all',
    })
    toast.success(isEditMode ? 'روایت با موفقیت به‌روزرسانی شد.' : 'روایت با موفقیت ثبت شد.')
    resetErrors()
    form.value = { title: '', description: '', missionaryRequestId: null }
    files.value = []
    close?.()
  } catch {
    toast.error('ثبت روایت با خطا مواجه شد.')
  }
}
</script>

<style lang="scss" scoped>
.create-narrative {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  text-align: start;
  padding-block: 0.25rem 0.5rem;

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

    &--two {
      @media (min-width: 640px) {
        grid-template-columns: 1fr 1fr;
      }
    }
  }

  &__upload {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  &__divider {
    border-block-end: 1px solid #ddd;
    margin-block: 0.25rem;
  }

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

  &__submit {
    min-width: 16rem;
    padding: 0 1.5rem;
  }
}
</style>
