<template>
  <UFormField :label="label">
    <UInputDate ref="inputDateRef" v-model="dateValue" :disabled="disabled">
      <template #trailing>
        <UPopover :reference="inputDateRef?.inputsRef[3]?.$el">
          <UButton
            color="neutral"
            variant="link"
            size="sm"
            icon="i-lucide-calendar"
            :aria-label="$t('applicationForms.formElements.selectDate')"
            class="px-0"
          />
          <template #content>
            <UCalendar v-model="dateValue" class="p-2" />
          </template>
        </UPopover>
      </template>
    </UInputDate>
  </UFormField>
</template>

<script setup lang="ts">
import type { FormOptionDto } from '~~/.api-client'
import type { CalendarDate } from '@internationalized/date'
import { parseDate } from '@internationalized/date'

const props = defineProps<{
  label?: string
  formOptions: FormOptionDto[]
  disabled?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:formOptions', value: FormOptionDto[]): void
}>()

const inputDateRef = useTemplateRef('inputDateRef')

const dateValue = computed({
  get: () => {
    const value = props.formOptions[0]?.value ?? ''
    if (!value) return null
    try {
      return parseDate(value)
    } catch {
      return null
    }
  },
  set: (val: CalendarDate | null) => {
    const firstOption = props.formOptions[0]
    if (firstOption) {
      const updatedModelValue = [...props.formOptions]
      updatedModelValue[0] = {
        ...firstOption,
        value: val ? val.toString() : ''
      }
      emit('update:formOptions', updatedModelValue)
    }
  }
})
</script>
