<script setup lang="ts">
import { ref, computed } from 'vue'
import { Calendar } from '@/components/ui/calendar'
import { Button } from '@/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { CalendarIcon } from 'lucide-vue-next'
import { cn } from '@/lib/utils'
import { CalendarDate, type DateValue } from '@internationalized/date'

interface Props {
  modelValue?: Date | string | null
  placeholder?: string
  disabled?: boolean
  format?: string
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Pick a date',
  format: 'PPP',
})

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

const placeholder = ref<DateValue>(new CalendarDate(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()))

const value = computed<DateValue | undefined>({
  get: () => {
    if (!props.modelValue) return undefined
    const date = props.modelValue instanceof Date ? props.modelValue : new Date(props.modelValue)
    return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
  },
  set: (dateValue) => {
    if (!dateValue) {
      emit('update:modelValue', null)
      return
    }
    const jsDate = new Date(dateValue.year, dateValue.month - 1, dateValue.day)
    emit('update:modelValue', jsDate)
  },
})

const formatDate = (dateValue: DateValue | undefined) => {
  if (!dateValue) return props.placeholder
  const date = new Date(dateValue.year, dateValue.month - 1, dateValue.day)
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })
}
</script>

<template>
  <Popover>
    <PopoverTrigger as-child>
      <Button
        variant="outline"
        :class="cn(
          'w-full justify-start text-left font-normal',
          !value && 'text-muted-foreground'
        )"
        :disabled="disabled"
      >
        <CalendarIcon class="mr-2 h-4 w-4" />
        {{ formatDate(value) }}
      </Button>
    </PopoverTrigger>
    <PopoverContent class="w-auto p-0">
      <Calendar v-model="value" :placeholder="placeholder" />
    </PopoverContent>
  </Popover>
</template>
