<template>
  <Teleport to="body">
    <div v-if="visible" class="modal modal-open" @click.self="$emit('close')">
      <div class="modal-box max-w-sm">
        <h3 class="font-bold text-lg mb-4">
          Modifier le document
        </h3>

        <div class="space-y-4">
          <label class="form-control w-full">
            <div class="label">
              <span class="label-text">Nom</span>
            </div>
            <input
              v-model="form.name"
              type="text"
              class="input input-bordered input-sm md:input-md w-full"
            >
          </label>

          <label class="form-control w-full">
            <div class="label">
              <span class="label-text">Type</span>
            </div>
            <select
              v-model="form.type"
              class="select select-bordered select-sm md:select-md w-full"
            >
              <option v-for="t in DOCUMENT_TYPES" :key="t.value" :value="t.value">
                {{ t.label }}
              </option>
            </select>
          </label>
        </div>

        <div class="modal-action">
          <button type="button" class="btn btn-ghost btn-sm md:btn-md" @click="$emit('close')">
            Annuler
          </button>
          <button
            type="button"
            class="btn btn-primary btn-sm md:btn-md"
            :disabled="saving"
            @click="save"
          >
            <span v-if="saving" class="loading loading-spinner loading-xs" />
            Sauvegarder
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { reactive, watch, ref } from 'vue'
import { DOCUMENT_TYPES } from '~/shared/documentTypes'
import type { Document } from '~/composables/useDocuments'

const props = defineProps<{
  visible: boolean
  document: Document | null
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'updated', data: { name: string; type: string }): void
}>()

const form = reactive({ name: '', type: 'documentation' })
const saving = ref(false)

watch(
  () => props.document,
  (doc) => {
    if (doc) {
      form.name = doc.name || ''
      form.type = doc.type || 'documentation'
    }
  },
  { immediate: true },
)

const save = () => {
  if (!form.name.trim()) return
  saving.value = true
  emit('updated', { name: form.name.trim(), type: form.type })
  saving.value = false
}
</script>
