<script setup lang="ts">
// helpers
import { format } from 'date-fns'
// icons
import { Calendar as CalendarIcon } from 'lucide-vue-next'
// components
import { Button } from '~/components/pub/ui/button'
import { Calendar } from '~/components/pub/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '~/components/pub/ui/popover'

const props = defineProps<{
  placeholder?: string
  modelValue?: Date | string | undefined
}>()

const emit = defineEmits<{
  'update:modelValue': [value: Date | string | undefined]
}>()

const date = ref<Date | any>(undefined)

// Sync prop to local state
watch(
  () => props.modelValue,
  (value) => {
    if (value instanceof Date) {
      date.value = value
    } else if (typeof value === 'string' && value) {
      date.value = value
    } else {
      date.value = undefined
    }
  },
  { immediate: true }
)

watch(date, (value) => {
  const newValue = format(value, 'yyyy-MM-dd')
  emit('update:modelValue', newValue)
})
</script>

<template>
  <div class="flex flex-col space-y-2">
    <Popover>
      <PopoverTrigger as-child>
        <Button variant="outline" class="bg-white border-gray-400 font-normal text-right h-[40px] w-full">
          <div class="flex justify-between items-center w-full">
            <p v-if="date">{{ format(date, 'PPP') }}</p>
            <p v-else class="text-sm text-black text-opacity-50">{{ props.placeholder || 'Tanggal' }}</p>
            <CalendarIcon class="h-4 w-4 ml-2" />
          </div>
        </Button>
      </PopoverTrigger>
      <PopoverContent class="w-auto p-0">
        <Calendar v-model="date" mode="single" />
      </PopoverContent>
    </Popover>
  </div>
</template>
