<script setup lang="ts">
import { ref, computed } from 'vue'
import { getColombianHolidays, isHoliday } from '@/services/calendar'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { ChevronLeft, ChevronRight } from 'lucide-vue-next'

const today = new Date()
const currentYear = ref(today.getFullYear())
const currentMonth = ref(today.getMonth())
const selectedDate = ref<Date | null>(null)

const MONTHS = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre']
const WEEKDAYS = ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb']

const holidays = computed(() => {
  const h = getColombianHolidays(currentYear.value)
  return new Map(h.map(h => [`${h.date.getFullYear()}-${h.date.getMonth()}-${h.date.getDate()}`, h.name]))
})

const weeks = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  const firstDay = new Date(year, month, 1).getDay()
  const totalDays = new Date(year, month + 1, 0).getDate()
  const days: (number | null)[] = Array.from({ length: 42 }, (_, i) => {
    const d = i - firstDay + 1
    return d > 0 && d <= totalDays ? d : null
  })
  const weeks: (number | null)[][] = []
  for (let i = 0; i < days.length; i += 7) weeks.push(days.slice(i, i + 7))
  return weeks
})

const selectedHoliday = computed(() => {
  if (!selectedDate.value) return null
  const h = isHoliday(selectedDate.value)
  return h.holiday ? h.name : null
})

function isWeekend(date: Date): boolean {
  return date.getDay() === 0 || date.getDay() === 6
}

function selectDay(day: number) {
  selectedDate.value = new Date(currentYear.value, currentMonth.value, day)
}

function prevMonth() {
  if (currentMonth.value === 0) { currentMonth.value = 11; currentYear.value-- }
  else currentMonth.value--
}
function nextMonth() {
  if (currentMonth.value === 11) { currentMonth.value = 0; currentYear.value++ }
  else currentMonth.value++
}

function dayClasses(day: number | null) {
  if (day === null) return 'text-muted-foreground/20 cursor-default'
  const d = new Date(currentYear.value, currentMonth.value, day)
  const key = `${currentYear.value}-${currentMonth.value}-${day}`
  const isHol = holidays.value.has(key)
  const isToday = day === today.getDate() && currentMonth.value === today.getMonth() && currentYear.value === today.getFullYear()
  const isSel = selectedDate.value?.getDate() === day && selectedDate.value?.getMonth() === currentMonth.value && selectedDate.value?.getFullYear() === currentYear.value
  const wknd = isWeekend(d)

  let cls = 'cursor-pointer hover:bg-accent rounded-md'
  if (isToday) cls += ' bg-primary/10 text-primary font-bold'
  else if (wknd) cls += ' text-muted-foreground/50'
  else if (isHol) cls += ' text-primary'

  if (isSel) cls += ' ring-2 ring-primary ring-inset'
  return cls
}
</script>

<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-2">
        <Button variant="outline" size="icon" @click="prevMonth">
          <ChevronLeft class="size-4" />
        </Button>
        <h2 class="text-lg font-bold min-w-[180px]">{{ MONTHS[currentMonth] }} {{ currentYear }}</h2>
        <Button variant="outline" size="icon" @click="nextMonth">
          <ChevronRight class="size-4" />
        </Button>
      </div>
      <Button variant="outline" size="sm" @click="currentMonth = today.getMonth(); currentYear = today.getFullYear()">Hoy</Button>
    </div>

    <Card>
      <CardContent class="p-4">
        <div class="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
          <div v-for="w in WEEKDAYS" :key="w" class="text-center text-[11px] font-semibold text-muted-foreground uppercase tracking-wider py-2 bg-card">
            {{ w }}
          </div>
          <template v-for="(week, wi) in weeks" :key="wi">
            <div v-for="(day, di) in week" :key="`${wi}-${di}`"
              :class="[
                'aspect-square flex flex-col items-center justify-center text-sm bg-card transition-colors',
                dayClasses(day)
              ]"
              @click="day && selectDay(day)"
            >
              <template v-if="day">
                <span class="leading-none">{{ day }}</span>
                <span v-if="holidays.get(`${currentYear}-${currentMonth}-${day}`)" class="text-[8px] leading-tight truncate max-w-full px-0.5 opacity-70">
                  {{ holidays.get(`${currentYear}-${currentMonth}-${day}`)!.slice(0, 3) }}
                </span>
              </template>
            </div>
          </template>
        </div>

        <div class="flex gap-4 mt-3 text-xs text-muted-foreground">
          <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-border" /> Laboral</span>
          <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-muted" /> Fin de semana</span>
          <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-primary" /> Feriado</span>
        </div>
      </CardContent>
    </Card>

    <div v-if="selectedDate" class="text-sm text-muted-foreground">
      <span class="capitalize font-medium text-foreground">
        {{ selectedDate.toLocaleDateString('es-CO', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) }}
      </span>
      <span v-if="selectedHoliday"> — <Badge variant="secondary" class="text-xs">Feriado: {{ selectedHoliday }}</Badge></span>
      <span v-else-if="isWeekend(selectedDate)"> — Fin de semana</span>
      <span v-else> — Día laboral</span>
    </div>
  </div>
</template>
