<script setup lang="ts">
import * as DE from '~/components/pub/my-ui/doc-entry'
import Separator from '~/components/pub/ui/separator/Separator.vue'
import Nav from '~/components/pub/my-ui/nav-footer/cl-sa.vue'
import * as CB from '~/components/pub/my-ui/combobox'

// import { bigTimeUnitCodes } from '~/lib/constants'

import { type Medicine } from '~/models/medicine';
import type { PrescriptionItem } from '~/models/prescription-item'

const props = defineProps<{
  data: PrescriptionItem
  medicines: Medicine[]
}>()

const { medicines } = toRefs(props)
const medicineItems = ref<CB.Item[]>([])
const medicineForm = computed(() => {
  const medicine = props.medicines.find(m => m.code === props.data.medicine_code)
  return medicine ? medicine.medicineForm?.name : '--tidak diketahui--'
})

type ClickType = 'close' | 'save'
type Item = {
  value: string
  label: string
}

if(!props.data.intervalUnit_code) {
  props.data.intervalUnit_code = 'day'
}

const emit = defineEmits<{
  close: [],
  save: [data: PrescriptionItem],
  'update:searchText': [value: string]
}>()

watch(medicines, (data) => {
  medicineItems.value = CB.objectsToItems(data, 'code', 'name')
})

function navClick(type: ClickType) {
  if (type === 'close') {
    emit('close')
  } else if (type === 'save') {
    emit('save', props.data)
  }
}

function searchMedicineText(value: string) {
  emit('update:searchText', value)
}
</script>

<template>
  <DE.Block :colCount="4" :cellFlex="false">
    <DE.Cell :colSpan="4">
      <DE.Label>Nama</DE.Label>
      <DE.Field>
        <CB.Combobox
          v-model="data.medicine_code"
          :items="medicineItems"
          @update:searchText="searchMedicineText"
        />
      </DE.Field>
    </DE.Cell>
    <DE.Cell>
      <DE.Label>Frequensi</DE.Label>
      <DE.Field><Input type="number" v-model.number="data.frequency" /></DE.Field>
    </DE.Cell>
    <DE.Cell>
      <DE.Label>Dosis</DE.Label>
      <DE.Field><Input type="number" v-model.number="data.dose" /></DE.Field>
    </DE.Cell>
    <!-- <DE.Cell>
      <DE.Label>Interval</DE.Label>
      <DE.Field>
        <Select
          v-model="data.intervalUnit_code"
          :items="bigTimeUnitCodeItems"
        />
      </DE.Field>
    </DE.Cell> -->
    <DE.Cell>
      <DE.Label>Total</DE.Label>
      <DE.Field>
        <Input type="number" v-model="data.quantity" />
      </DE.Field>
    </DE.Cell>
    <DE.Cell>
        <DE.Label>Sediaan</DE.Label>
        <DE.Field><Input :value="medicineForm" readonly /></DE.Field>
    </DE.Cell>
    <DE.Cell :colSpan="4">
        <DE.Label>Cara Pakai</DE.Label>
        <DE.Field><Input v-model="data.usage" /></DE.Field>
    </DE.Cell>
  </DE.Block>
  <Separator class="my-5" />
  <div class="flex justify-center">
    <Nav @click="navClick" />
  </div>
</template>
