<template>
    <div
        class="flex cursor-pointer items-stretch gap-3 rounded-[10px] bg-white px-3 py-2.5 transition-colors hover:shadow-sm sm:px-4"
        :class="selected ? 'ring-2 ring-primary-500' : ''"
        @click="emit('click')"
    >
        <!-- Content -->
        <div class="min-w-0 flex-1">
            <!-- Row 1: checkbox + code + flag -->
            <div class="flex items-center gap-1.5">
                <div
                    class="flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded border-2 transition-colors"
                    :class="selected ? 'border-primary-500 bg-primary-500' : 'border-neutral-300 hover:border-primary-400'"
                    @click.stop="emit('toggle-select', task.id)"
                >
                    <Icon v-if="selected" name="mdi:check" size="12" class="text-white" />
                </div>
                <span
                    v-if="task.project && task.number"
                    class="text-xs font-semibold"
                    :class="showProjectColor ? '' : 'text-neutral-400'"
                    :style="showProjectColor && task.project.color ? { color: task.project.color } : {}"
                >
                    {{ task.project.code }}-{{ task.number }}
                </span>
                <Icon
                    v-if="task.priority?.label === 'Haute'"
                    name="mdi:flag-variant"
                    class="h-3.5 w-3.5 text-red-600"
                />
            </div>
            <!-- Row 2: title -->
            <h4 class="mt-1 text-sm font-semibold text-neutral-900">{{ task.title }}</h4>
            <!-- Row 3: tags + status + deadline/calendar/recurrence -->
            <div class="mt-2 flex flex-wrap items-center gap-1.5">
                <span
                    v-for="tag in task.tags"
                    :key="tag.id"
                    class="rounded-full px-2 py-0.5 text-[10px] font-semibold text-white"
                    :style="{ backgroundColor: tag.color }"
                >
                    {{ tag.label }}
                </span>
                <span
                    v-if="task.status"
                    class="text-xs font-semibold uppercase text-neutral-400"
                >
                    {{ task.status.label }}
                </span>
                <span v-else class="text-xs font-semibold uppercase text-neutral-300">
                    Backlog
                </span>
                <!-- Deadline badge -->
                <span
                    v-if="task.deadline"
                    class="rounded-full px-2 py-0.5 text-[10px] font-semibold text-white"
                    :style="{ backgroundColor: deadlineColor }"
                    :title="task.deadline"
                >
                    {{ formatDeadline(task.deadline) }}
                </span>
                <!-- Calendar sync icon -->
                <Icon
                    v-if="task.syncToCalendar"
                    :name="task.calendarSyncError ? 'mdi:alert-circle' : 'mdi:calendar-check'"
                    :class="task.calendarSyncError ? 'text-red-500' : 'text-green-500'"
                    size="13"
                />
                <!-- Recurrence icon -->
                <Icon
                    v-if="task.recurrence"
                    name="mdi:repeat"
                    class="text-blue-500"
                    size="13"
                />
            </div>
        </div>

        <!-- Right: timer top, avatar bottom -->
        <div class="flex shrink-0 flex-col items-end justify-between self-stretch gap-1">
            <MalioButtonIcon
                :icon="isTimerOnTask ? 'mdi:stop-circle-outline' : 'mdi:play-circle-outline'"
                :aria-label="isTimerOnTask ? 'Arrêter le timer' : 'Démarrer le timer'"
                variant="ghost"
                icon-size="20"
                :button-class="isTimerOnTask ? 'shrink-0 text-[#F18619] hover:text-[#d97314]' : 'shrink-0 text-neutral-400 hover:text-primary-500'"
                @click.stop="isTimerOnTask ? timerStore.stop() : timerStore.startFromTask(task)"
            />
            <UserAvatar
                v-if="task.assignee"
                :user="task.assignee"
                size="xs"
            />
            <span
                v-else
                class="flex h-5 w-5 items-center justify-center rounded-full bg-neutral-200 text-neutral-400"
            >
                <Icon name="mdi:account-outline" size="14" />
            </span>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { Task } from '~/services/dto/task'

const props = withDefaults(defineProps<{
    task: Task
    showProjectColor?: boolean
    selected?: boolean
}>(), {
    showProjectColor: false,
    selected: false,
})

const emit = defineEmits<{
    (e: 'click'): void
    (e: 'toggle-select', taskId: number): void
}>()

const timerStore = useTimerStore()

const deadlineColor = computed(() => {
    if (!props.task.deadline) return ''
    const daysLeft = (new Date(props.task.deadline).getTime() - Date.now()) / 86400000
    if (daysLeft < 0) return '#DC2626'
    if (daysLeft < 2) return '#F59E0B'
    return '#9CA3AF'
})

function formatDeadline(d: string): string {
    return new Date(d).toLocaleDateString('fr-FR', { month: 'short', day: 'numeric' })
}

const isTimerOnTask = computed(() => {
    const entry = timerStore.activeEntry
    if (!entry?.task) return false
    const entryTaskId = typeof entry.task === 'string'
        ? entry.task
        : (entry.task['@id'] ?? entry.task.id)
    const taskId = props.task['@id'] ?? props.task.id
    return entryTaskId === taskId || entryTaskId === `/api/tasks/${props.task.id}`
})
</script>
