<script setup lang="ts">
const emit = defineEmits<{
  submit: [payload: { history_entry_type_id: number; body: string; occurred_at: string | null }]
}>()

const { types, fetchTypes } = useHistoryTypes()
await fetchTypes()

const typeId = ref<number | null>(types.value[0]?.id ?? null)
const body = ref('')
const occurredAt = ref('') // datetime-local value: "YYYY-MM-DDTHH:MM"
const submitting = ref(false)

const selectedType = computed(() => types.value.find(t => t.id === typeId.value) ?? null)
const requiresDatetime = computed(() => selectedType.value?.requires_datetime ?? false)

const submit = async () => {
  if (!body.value.trim() || typeId.value === null) return
  if (requiresDatetime.value && !occurredAt.value) return

  submitting.value = true
  // Backend expects a naive local datetime with seconds (Y-m-d\TH:i:s); the
  // datetime-local input omits seconds, so append :00.
  const occurred_at = requiresDatetime.value && occurredAt.value ? `${occurredAt.value}:00` : null
  emit('submit', { history_entry_type_id: typeId.value, body: body.value, occurred_at })
  body.value = ''
  occurredAt.value = ''
  submitting.value = false
}
</script>

<template>
  <form @submit.prevent="submit" class="border border-gray-200 bg-white p-4 space-y-3">
    <div class="flex gap-3 items-start">
      <div class="shrink-0">
        <label class="block text-xs font-medium text-gray-600 mb-1">Typ</label>
        <select v-model="typeId" class="border border-gray-300 px-2 py-1.5 text-sm">
          <option v-for="t in types" :key="t.id" :value="t.id">{{ t.name }}</option>
        </select>
      </div>
      <div v-if="requiresDatetime" class="shrink-0">
        <label class="block text-xs font-medium text-gray-600 mb-1">Datum/Uhrzeit</label>
        <input
          v-model="occurredAt"
          type="datetime-local"
          class="border border-gray-300 px-2 py-1.5 text-sm"
        />
      </div>
      <div class="flex-1">
        <label class="block text-xs font-medium text-gray-600 mb-1">Eintrag</label>
        <textarea
          v-model="body"
          rows="3"
          placeholder="Notiz eingeben…"
          class="w-full border border-gray-300 px-3 py-2 text-sm resize-y"
        />
      </div>
    </div>
    <div class="flex justify-end">
      <button
        type="submit"
        :disabled="submitting || !body.trim() || typeId === null || (requiresDatetime && !occurredAt)"
        class="bg-blue-600 text-white px-4 py-1.5 text-sm hover:bg-blue-700 disabled:opacity-50"
      >
        Eintrag speichern
      </button>
    </div>
  </form>
</template>
