<template>
    <div class="rounded-lg border border-neutral-200 bg-white">
        <!-- Header -->
        <div class="flex items-center justify-between border-b border-neutral-200 px-4 py-3">
            <button class="rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100" @click="shiftMonth(-1)">
                <Icon name="mdi:chevron-left" size="22" />
            </button>
            <p class="text-lg font-semibold capitalize text-neutral-900">{{ monthLabel }}</p>
            <button class="rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100" @click="shiftMonth(1)">
                <Icon name="mdi:chevron-right" size="22" />
            </button>
        </div>

        <!-- Weekday headers -->
        <div class="grid grid-cols-7 border-b border-neutral-100 text-center text-xs font-medium text-neutral-400">
            <div v-for="d in weekdays" :key="d" class="py-2">{{ d }}</div>
        </div>

        <!-- Grid -->
        <div class="grid grid-cols-7">
            <div
                v-for="cell in cells"
                :key="cell.key"
                class="min-h-[92px] border-b border-r border-neutral-100 p-1.5"
                :class="cell.holiday ? 'bg-amber-50' : (cell.inMonth ? 'bg-white' : 'bg-neutral-50')"
                :title="cell.holiday ?? undefined"
            >
                <div class="mb-1 flex items-center gap-1">
                    <span v-if="cell.holiday" class="flex min-w-0 flex-1 items-center gap-1 text-[10px] font-medium text-amber-700">
                        <Icon name="mdi:star-four-points-outline" size="11" class="flex-shrink-0" />
                        <span class="truncate">{{ cell.holiday }}</span>
                    </span>
                    <span v-else class="flex-1" />
                    <span class="flex-shrink-0 text-xs" :class="cell.isToday ? 'font-bold text-orange-500' : 'text-neutral-400'">
                        {{ cell.day }}
                    </span>
                </div>
                <div class="flex flex-col gap-1">
                    <span
                        v-for="abs in cell.absences"
                        :key="abs.id"
                        class="truncate rounded px-1 py-0.5 text-[11px] font-medium text-white"
                        :style="{ backgroundColor: abs.status === 'pending' ? typeColor(abs.type) + 'aa' : typeColor(abs.type) }"
                        :title="`${abs.user.username} · ${abs.label} (${statusLabel(abs.status)})`"
                    >
                        {{ abs.user.username }}
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { AbsenceRequest } from '~/services/dto/absence'
import { useAbsenceService } from '~/services/absences'
import { useAbsenceHelpers } from '~/composables/useAbsenceHelpers'

const props = defineProps<{
    absences: AbsenceRequest[]
}>()

const emit = defineEmits<{
    'range-change': [from: string, to: string]
}>()

const service = useAbsenceService()
const { typeColor, statusLabel } = useAbsenceHelpers()

const holidays = ref<Record<string, string>>({})

const weekdays = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim']

const cursor = ref(startOfMonth(new Date()))

const monthLabel = computed(() =>
    cursor.value.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' }),
)

type Cell = { key: string; day: number; date: Date; inMonth: boolean; isToday: boolean; holiday: string | null; absences: AbsenceRequest[] }

function startOfMonth(d: Date): Date {
    return new Date(d.getFullYear(), d.getMonth(), 1)
}

function ymd(d: Date): string {
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

// First Monday on/before the 1st of the month
function gridStart(month: Date): Date {
    const first = startOfMonth(month)
    const dow = (first.getDay() + 6) % 7 // 0 = Monday
    const start = new Date(first)
    start.setDate(first.getDate() - dow)
    return start
}

const visibleRange = computed(() => {
    const start = gridStart(cursor.value)
    const end = new Date(start)
    end.setDate(start.getDate() + 41) // 6 weeks grid
    return { start, end }
})

const cells = computed<Cell[]>(() => {
    const { start } = visibleRange.value
    const today = ymd(new Date())
    const result: Cell[] = []
    for (let i = 0; i < 42; i++) {
        const date = new Date(start)
        date.setDate(start.getDate() + i)
        const key = ymd(date)
        result.push({
            key,
            day: date.getDate(),
            date,
            inMonth: date.getMonth() === cursor.value.getMonth(),
            isToday: key === today,
            holiday: holidays.value[key] ?? null,
            absences: props.absences.filter(a => key >= a.startDate.slice(0, 10) && key <= a.endDate.slice(0, 10)),
        })
    }
    return result
})

async function emitRange() {
    const { start, end } = visibleRange.value
    emit('range-change', ymd(start), ymd(end))
    try {
        holidays.value = await service.getPublicHolidays(ymd(start), ymd(end))
    } catch {
        holidays.value = {}
    }
}

function shiftMonth(delta: number) {
    cursor.value = new Date(cursor.value.getFullYear(), cursor.value.getMonth() + delta, 1)
    emitRange()
}

onMounted(emitRange)
</script>
