<template>
    <MalioDrawer v-model="open" drawer-class="max-w-lg">
        <template #header>
            <h2 class="text-xl font-bold">{{ $t('absences.detail.title') }}</h2>
        </template>
        <div v-if="request" class="flex flex-col gap-5">
            <!-- Hero -->
            <div class="overflow-hidden rounded-xl border border-neutral-200 shadow-sm">
                <div
                    class="flex items-start gap-3 p-4"
                    :style="{ borderLeft: `4px solid ${typeColor(request.type)}` }"
                >
                    <span
                        class="mt-0.5 flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-full"
                        :style="{ backgroundColor: tint(request.type), color: typeColor(request.type) }"
                    >
                        <Icon name="mdi:calendar-account" size="22" />
                    </span>
                    <div class="min-w-0 flex-1">
                        <p class="truncate text-lg font-semibold text-neutral-900">{{ request.label }}</p>
                        <p class="mt-0.5 flex items-center gap-1.5 text-sm text-neutral-500">
                            <Icon name="mdi:calendar-range" size="15" />
                            {{ formatRange(request) }}
                        </p>
                    </div>
                    <StatusBadge
                        class="flex-shrink-0"
                        :label="statusLabel(request.status)"
                        :variant="statusVariant(request.status)"
                        :icon="statusIcon(request.status)"
                    />
                </div>

                <dl class="grid grid-cols-2 divide-x divide-neutral-200 border-t border-neutral-200 bg-neutral-50">
                    <div class="flex items-center gap-2.5 p-3">
                        <span
                            v-if="request.user.avatarUrl"
                            class="h-9 w-9 flex-shrink-0 overflow-hidden rounded-full"
                        >
                            <img :src="request.user.avatarUrl" alt="" class="h-full w-full object-cover">
                        </span>
                        <span
                            v-else
                            class="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full bg-primary-100 text-xs font-semibold text-primary-600"
                        >
                            {{ initials }}
                        </span>
                        <div class="min-w-0">
                            <dt class="text-xs text-neutral-400">{{ $t('absences.table.employee') }}</dt>
                            <dd class="truncate text-sm font-medium text-neutral-800">{{ request.user.username }}</dd>
                        </div>
                    </div>
                    <div class="flex flex-col justify-center p-3">
                        <dt class="text-xs text-neutral-400">{{ $t('absences.table.days') }}</dt>
                        <dd class="text-sm font-semibold text-neutral-900">{{ formatDays(request.countedDays) }}</dd>
                    </div>
                </dl>
            </div>

            <!-- Reason -->
            <div v-if="request.reason" class="rounded-lg border border-neutral-200 p-3">
                <p class="mb-1 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-neutral-400">
                    <Icon name="mdi:comment-text-outline" size="14" />
                    {{ $t('absences.form.reason') }}
                </p>
                <p class="whitespace-pre-line text-sm text-neutral-800">{{ request.reason }}</p>
            </div>

            <!-- Rejection -->
            <div
                v-if="request.status === 'rejected' && request.rejectionReason"
                class="rounded-lg border border-red-200 bg-red-50 p-3"
            >
                <p class="mb-1 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-red-500">
                    <Icon name="mdi:close-circle-outline" size="14" />
                    {{ $t('absences.detail.rejectionReason') }}
                </p>
                <p class="text-sm text-red-700">{{ request.rejectionReason }}</p>
            </div>

            <!-- Justification -->
            <a
                v-if="request.justificationUrl"
                :href="request.justificationUrl"
                target="_blank"
                rel="noopener"
                class="flex items-center gap-2 rounded-lg border border-neutral-200 p-3 text-sm font-medium text-neutral-700 transition hover:border-primary-300 hover:bg-primary-50"
            >
                <Icon name="mdi:file-document-outline" size="20" class="text-primary-500" />
                <span class="flex-1 truncate">{{ request.justificationFileName || $t('absences.detail.downloadJustification') }}</span>
                <Icon name="mdi:download" size="16" class="text-neutral-400" />
            </a>

            <!-- Timeline -->
            <div>
                <p class="mb-3 text-xs font-medium uppercase tracking-wide text-neutral-400">
                    {{ $t('absences.detail.timeline') }}
                </p>
                <ol class="relative ml-1 border-l border-neutral-200 pl-5">
                    <li class="mb-4 last:mb-0">
                        <span class="absolute -left-[7px] mt-0.5 h-3.5 w-3.5 rounded-full border-2 border-white bg-primary-500 ring-1 ring-primary-200" />
                        <p class="text-sm font-medium text-neutral-800">{{ $t('absences.detail.created') }}</p>
                        <p class="text-xs text-neutral-400">{{ formatDateTime(request.createdAt) }}</p>
                    </li>
                    <li v-if="request.reviewedAt" class="last:mb-0">
                        <span
                            class="absolute -left-[7px] mt-0.5 h-3.5 w-3.5 rounded-full border-2 border-white ring-1"
                            :class="request.status === 'rejected'
                                ? 'bg-red-500 ring-red-200'
                                : 'bg-green-500 ring-green-200'"
                        />
                        <p class="text-sm font-medium text-neutral-800">
                            {{ statusLabel(request.status) }}
                            <span v-if="request.reviewedBy" class="font-normal text-neutral-500">
                                · {{ $t('absences.detail.reviewed', { name: request.reviewedBy.username }) }}
                            </span>
                        </p>
                        <p class="text-xs text-neutral-400">{{ formatDateTime(request.reviewedAt) }}</p>
                    </li>
                </ol>
            </div>

            <div v-if="canCancel" class="flex justify-end border-t border-neutral-100 pt-4">
                <MalioButton
                    :label="$t('absences.detail.cancel')"
                    variant="danger"
                    icon-name="mdi:cancel"
                    icon-position="left"
                    :disabled="cancelling"
                    @click="onCancel"
                />
            </div>
        </div>
    </MalioDrawer>
</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<{
    modelValue: boolean
    request: AbsenceRequest | null
    canCancel?: boolean
}>()

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

const { t } = useI18n()
const service = useAbsenceService()
const { statusLabel, statusVariant, statusIcon, formatRange, formatDays, typeColor } = useAbsenceHelpers()

const open = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

const cancelling = ref(false)

const initials = computed(() => {
    const name = props.request?.user.username ?? ''
    return name.slice(0, 2).toUpperCase() || '?'
})

/** Type colour at ~12% opacity for soft backgrounds. */
function tint(type: AbsenceRequest['type']): string {
    return `${typeColor(type)}1f`
}

function formatDateTime(iso: string | null): string {
    if (!iso) return ''
    const d = new Date(iso)
    if (isNaN(d.getTime())) return ''
    return d.toLocaleString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

async function onCancel() {
    if (!props.request) return
    if (!confirm(t('absences.detail.cancelConfirm'))) return
    cancelling.value = true
    try {
        await service.cancel(props.request.id)
        emit('cancelled')
        open.value = false
    } finally {
        cancelling.value = false
    }
}
</script>
