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

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

interface Props {
  modelValue?: string | null
  placeholder?: string
  disabled?: boolean
  min?: string
  max?: string
}

interface Emits {
  (e: 'update:modelValue', value: string | null): void
}

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

const emit = defineEmits<Emits>()

// Convert string date to DateValue for the calendar component
const calendarValue = computed(() => {
  if (!props.modelValue) return undefined
  try {
    return parseDate(props.modelValue)
  } catch {
    return undefined
  }
})

const handleDateSelect = (date: DateValue | undefined) => {
  if (date) {
    // Convert DateValue to ISO string format (YYYY-MM-DD)
    const isoString = date.toString()
    emit('update:modelValue', isoString)
  } else {
    emit('update:modelValue', null)
  }
}

const formatDate = (dateString: string | null) => {
  if (!dateString) return ''
  
  try {
    const dateObj = new Date(dateString)
    return dateObj.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  } catch {
    return dateString
  }
}
</script>