<script setup>
import { computed, ref } from 'vue'
import Card from '@/components/ui/Card.vue'
import VitalsEntryForm from '@/components/patient/VitalsEntryForm.vue'
import { observationCodeLabel } from '@/api/normalize'
import { submitVitalsObservations } from '@/api/encounters'

const props = defineProps({
  encounterId: { type: String, required: true },
  observations: { type: Array, default: () => [] },
})

const emit = defineEmits(['recorded'])

const showVitalsForm = ref(false)
const submitting = ref(false)
const submitError = ref('')

const latestByCode = computed(() => {
  const map = new Map()
  for (const obs of props.observations) {
    const existing = map.get(obs.observationCode)
    if (!existing || new Date(obs.recordedAt) > new Date(existing.recordedAt)) {
      map.set(obs.observationCode, obs)
    }
  }
  return [...map.values()].sort((a, b) =>
    observationCodeLabel(a.observationCode).localeCompare(observationCodeLabel(b.observationCode)),
  )
})

async function onSubmit(observations) {
  submitError.value = ''
  submitting.value = true
  try {
    await submitVitalsObservations(props.encounterId, observations)
    showVitalsForm.value = false
    emit('recorded')
  } catch (error) {
    submitError.value = error.message
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <Card>
    <template #header>
      <div class="mb-4 flex flex-wrap items-center justify-between gap-2">
        <h2 class="text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Latest Vitals
        </h2>
        <button
          type="button"
          class="text-xs text-blue-600 hover:underline dark:text-blue-400"
          @click="showVitalsForm = !showVitalsForm"
        >
          {{ showVitalsForm ? 'Cancel' : 'Record Vitals' }}
        </button>
      </div>
    </template>

    <Transition name="fade">
      <VitalsEntryForm
        v-if="showVitalsForm"
        class="mb-6"
        :submitting="submitting"
        :error="submitError"
        @submit="onSubmit"
      />
    </Transition>

    <div v-if="latestByCode.length" class="grid grid-cols-2 gap-4 sm:grid-cols-3">
      <div
        v-for="obs in latestByCode"
        :key="obs.id ?? obs.observationCode"
        class="rounded-lg bg-gray-50 p-4 dark:bg-gray-800"
      >
        <div class="text-xs text-gray-500 dark:text-gray-400">
          {{ observationCodeLabel(obs.observationCode) }}
        </div>
        <div class="text-lg font-semibold text-gray-900 dark:text-white">
          {{ obs.value }}
          <span class="text-sm font-normal text-gray-500 dark:text-gray-400">{{ obs.unit }}</span>
        </div>
      </div>
    </div>
    <p v-else class="text-sm text-gray-500 dark:text-gray-400">No observations recorded</p>
  </Card>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.15s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
