<template>
  <div class="csf">
    <form class="csf__form" @submit.prevent="onSubmit">
      <div class="csf__row">
        <div class="csf__cell">
          <SelectField
            v-model="form.category"
            name="category"
            label="نوع خدمت"
            placeholder="نوع خدمت را انتخاب کنید"
            :options="serviceTypeOptions"
            option-label="label"
            option-value="value"
            :error="errors.category"
          />
        </div>
        <div class="csf__cell">
          <TextField
            v-model="form.subject"
            name="subject"
            label="عنوان خدمت"
            placeholder="عنوان خدمت را وارد کنید"
            :error="errors.subject"
          />
        </div>
      </div>

      <div class="csf__row">
        <div class="csf__cell csf__cell--full">
          <TextareaField
            v-model="form.message"
            name="message"
            label="توضیحات خود را وارد نمایید"
            :row="5"
            :error="errors.message"
          />
        </div>
      </div>

      <div class="csf__upload">
        <FileUploader
          v-model="files"
          accept="image/*,application/pdf"
          :max-files="3"
          @select="onFilesSelect"
          @error="onFileError"
        />
      </div>

      <div class="csf__divider" />

      <div class="csf__actions">
        <BaseButton
          type="submit"
          text="ثبت درخواست"
          custom-class="csf__submit"
          :loading="submitting"
          :disabled="uploadMutation.isPending.value"
        >
          <template #appendIcon>
            <SvgIcon name="arrow-left" :size="16" color="#fff" />
          </template>
        </BaseButton>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import * as yup from 'yup'
import { toast } from 'vue3-toastify'
import useYup from '@/composables/useYup'
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 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'

defineProps({
  submitting: { type: Boolean, default: false },
})

const emit = defineEmits(['submit', 'file-error'])

const serviceTypeOptions = [
  { value: 'خدمات رفاهی', label: 'خدمات رفاهی' },
  { value: 'خدمات آموزشی', label: 'خدمات آموزشی' },
]

const form = ref({
  category: '',
  subject: '',
  message: '',
})

// Items here are uploaded-media descriptors { id, name, size, url } — not raw
// File objects. We upload immediately on select (same pattern as
// AddAssignmentModal / SessionFormPage) and just collect the IDs at submit.
const files = ref([])

const schema = yup.object({
  category: yup.string().trim().required('نوع خدمت را انتخاب کنید'),
  subject: yup.string().trim().required('عنوان خدمت را وارد کنید'),
  message: yup
    .string()
    .trim()
    .min(5, 'توضیحات حداقل ۵ کاراکتر باشد')
    .required('توضیحات را وارد کنید'),
})

const { validate, errors } = useYup(schema)

const uploadMutation = useUploadMediaMutation()

const onFilesSelect = async (newFiles) => {
  for (const file of newFiles) {
    try {
      const fd = objectToFormData({ file, purpose: 'attachment', context: 'ticket' })
      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) => emit('file-error', msg)

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

  emit('submit', {
    category: payload.category,
    subject: payload.subject,
    message: payload.message,
    mediaIds: files.value.map((f) => f.id).filter((id) => id != null),
  })
}
</script>

<style lang="scss" scoped>
.csf {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  border-radius: 0.75rem;

  &__intro {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    padding: 0.5rem 0 1rem;
    border-bottom: 0.75px solid #ddd;
  }

  &__intro-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 0.625rem;
    background: rgba(255, 255, 255, 44%);
    box-shadow: 0 3px 7.35px rgba(245, 93, 109, 100%);
    flex-shrink: 0;
  }

  &__intro-text {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    text-align: end;
    gap: 0.125rem;
    flex: 1;

    @media (min-width: 768px) {
      align-items: center;
      text-align: center;
    }
  }

  &__intro-title {
    font-family: var(--font-family-fa);
    font-weight: 500;
    font-size: 1.05rem;
    color: #4c4c4c;
    margin: 0;
  }

  &__intro-desc {
    font-family: var(--font-family-fa);
    font-weight: 400;
    font-size: 0.75rem;
    color: #adadad;
    margin: 0;
  }

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

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

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

  &__cell {
    display: flex;
    flex-direction: column;

    @media (min-width: 768px) {
      grid-column: span 3;
    }

    &--full {
      grid-column: 1 / -1;
    }
  }

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

  &__divider {
    height: 0.75px;
    background: #ddd;
    margin-top: 0.25rem;
  }

  &__actions {
    display: flex;
    justify-content: center;

    @media (min-width: 768px) {
      justify-content: flex-end;
    }
  }

  &__submit {
    min-width: 14rem;
    height: 2.5rem;
    padding: 0 2.5rem;
  }
}
</style>
