<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Clock } 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 UiInput from '@/components/ui/input/Input.vue'
import UiLabel from '@/components/ui/label/Label.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 timeValue = computed({
  get() {
    return props.modelValue || '00:00'
  },
  set(value: string) {
    emit('update:modelValue', value)
  },
})

const formattedTime = computed(() => {
  return timeValue.value || ''
})

function handleTimeChange(time: string | number) {
  timeValue.value = typeof time === 'number' ? String(time) : time
}
</script>

<template>
  <UiPopover v-model:open="open">
    <UiPopoverTrigger as-child>
      <UiButton
        variant="outline"
        :class="cn(
          'w-full justify-start text-left font-normal',
          !modelValue && 'text-muted-foreground',
          props.class,
        )"
        :disabled="disabled"
      >
        <Clock class="mr-2 h-4 w-4" />
        {{ formattedTime || placeholder || '选择时间' }}
      </UiButton>
    </UiPopoverTrigger>
    <UiPopoverContent class="w-auto p-3" align="start">
      <div class="space-y-2">
        <UiLabel>时间</UiLabel>
        <UiInput
          type="time"
          :model-value="timeValue"
          @update:model-value="handleTimeChange"
          class="max-w-[150px]"
        />
      </div>
    </UiPopoverContent>
  </UiPopover>
</template>
