<script setup lang="ts">
import { ref, computed } from 'vue'
import { type HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { ChevronLeft, ChevronRight } from 'lucide-vue-next'

const props = defineProps<{
  modelValue?: Date
  class?: HTMLAttributes['class']
}>()

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

const viewDate = ref(new Date())

const monthNames = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre']
const dayNames = ['Do','Lu','Ma','Mi','Ju','Vi','Sa']

const daysInMonth = computed(() => new Date(viewDate.value.getFullYear(), viewDate.value.getMonth() + 1, 0).getDate())
const firstDay = computed(() => new Date(viewDate.value.getFullYear(), viewDate.value.getMonth(), 1).getDay())

const today = new Date()
const selectedDate = ref(props.modelValue)

function prevMonth() { viewDate.value = new Date(viewDate.value.getFullYear(), viewDate.value.getMonth() - 1, 1) }
function nextMonth() { viewDate.value = new Date(viewDate.value.getFullYear(), viewDate.value.getMonth() + 1, 1) }

function selectDay(d: number) {
  const date = new Date(viewDate.value.getFullYear(), viewDate.value.getMonth(), d)
  date.setHours(0, 0, 0, 0)
  selectedDate.value = date
  emit('update:modelValue', date)
}

function isSelected(d: number) {
  if (!selectedDate.value) return false
  return selectedDate.value.getFullYear() === viewDate.value.getFullYear() &&
    selectedDate.value.getMonth() === viewDate.value.getMonth() &&
    selectedDate.value.getDate() === d
}

function isToday(d: number) {
  return today.getFullYear() === viewDate.value.getFullYear() &&
    today.getMonth() === viewDate.value.getMonth() &&
    today.getDate() === d
}
</script>

<template>
  <div :class="cn('p-3', props.class)">
    <div class="flex items-center justify-between mb-2">
      <Button variant="ghost" size="icon" class="size-7" @click="prevMonth"><ChevronLeft class="size-4" /></Button>
      <span class="text-sm font-medium">{{ monthNames[viewDate.getMonth()] }} {{ viewDate.getFullYear() }}</span>
      <Button variant="ghost" size="icon" class="size-7" @click="nextMonth"><ChevronRight class="size-4" /></Button>
    </div>
    <div class="grid grid-cols-7 gap-0 text-center text-xs mb-1">
      <span v-for="d in dayNames" :key="d" class="text-muted-foreground py-1">{{ d }}</span>
    </div>
    <div class="grid grid-cols-7 gap-0 text-center text-sm">
      <span v-for="_ in firstDay" :key="'e'+_" />
      <button
        v-for="d in daysInMonth"
        :key="d"
        class="py-1.5 rounded hover:bg-muted transition-colors relative"
        :class="[isSelected(d) ? 'bg-primary text-primary-foreground hover:bg-primary' : '', isToday(d) && !isSelected(d) ? 'bg-accent text-accent-foreground' : '']"
        @click="selectDay(d)"
      >{{ d }}</button>
    </div>
  </div>
</template>
