<script setup lang="ts">
import type { DateValue } from '@internationalized/date'
import type { HTMLAttributes } from 'vue'
import { parseDate } from '@internationalized/date'
import { cn } from '@/lib/utils'
import { Calendar } from 'lucide-vue-next'
import { computed } from 'vue'
import UiButton from '@/components/ui/button/Button.vue'
import UiPopover from '@/components/ui/popover/Popover.vue'
import UiPopoverTrigger from '@/components/ui/popover/PopoverTrigger.vue'
import UiPopoverContent from '@/components/ui/popover/PopoverContent.vue'
import UiCalendar from '@/components/ui/calendar/Calendar.vue'

const props = defineProps<{
  modelValue?: string
  placeholder?: string
  class?: HTMLAttributes['class']
  disabled?: boolean
}>()

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

const open = defineModel<boolean>('open', { default: false })

const dateValue = computed<DateValue | undefined>({
  get() {
    if (props.modelValue) {
      try {
        return parseDate(props.modelValue.split('T')[0])
      }
      catch {
        return undefined
      }
    }
    return undefined
  },
  set(value) {
    if (value) {
      emit('update:modelValue', value.toString())
    }
    else {
      emit('update:modelValue', '')
    }
  },
})

const formattedDate = computed(() => {
  if (dateValue.value) {
    return dateValue.value.toString()
  }
  return ''
})

function handleSelect(date: DateValue | undefined) {
  if (date) {
    dateValue.value = date
    open.value = false
  }
}
</script>

<template>
  <UiPopover v-model:open="open">
    <UiPopoverTrigger as-child>
      <UiButton
        variant="outline"
        :class="cn(
          'w-full justify-start text-left font-normal',
          !dateValue && 'text-muted-foreground',
          props.class,
        )"
        :disabled="disabled"
      >
        <Calendar class="mr-2 h-4 w-4" />
        {{ formattedDate || placeholder || '选择日期' }}
      </UiButton>
    </UiPopoverTrigger>
    <UiPopoverContent class="w-auto p-0" align="start">
      <UiCalendar
        :model-value="dateValue"
        @update:model-value="handleSelect"
      />
    </UiPopoverContent>
  </UiPopover>
</template>
