<template>
    <Card as="li" :variant="isOverdue ? 'soft' : 'outlined'" :color="isOverdue ? 'error' : 'neutral'" padding="md"
        :class="[
            'chore-item',
            { 'is-completed': chore.is_completed, 'is-updating': chore.updating }
        ]">
        <div class="chore-content">
            <!-- Checkbox -->
            <div class="chore-checkbox">
                <input type="checkbox" :checked="chore.is_completed" @change.stop="emit('toggle-completion', chore)"
                    class="custom-checkbox" />
            </div>

            <!-- Main Info -->
            <div class="chore-details" @click="emit('open-details', chore)">
                <div class="details-header">
                    <span class="chore-name">{{ chore.name }}</span>
                    <div class="chore-badges">
                        <span v-if="chore.type === 'group'" class="badge type-badge">Group</span>
                        <span v-if="isOverdue" class="badge overdue-badge">Overdue</span>
                        <span v-else-if="isDueToday" class="badge due-today-badge">Due Today</span>
                    </div>
                </div>
                <p v-if="chore.description" class="chore-description">
                    {{ chore.description }}
                </p>
                <div class="details-footer">
                    <span v-if="dueInText" class="due-date-text">
                        <BaseIcon name="heroicons:calendar-20-solid" />
                        <span>{{ dueInText }}</span>
                    </span>
                    <span v-if="totalTime > 0" class="time-tracked-text">
                        <BaseIcon name="heroicons:clock-20-solid" />
                        <span>{{ formatDuration(totalTime) }}</span>
                    </span>
                </div>
            </div>

            <!-- Action Menu -->
            <div class="chore-actions">
                <Menu as="div" class="relative">
                    <MenuButton as="template">
                        <Button variant="ghost" size="sm" class="action-button">
                            <BaseIcon name="heroicons:ellipsis-vertical-20-solid" />
                        </Button>
                    </MenuButton>
                    <transition enter-active-class="transition duration-100 ease-out"
                        enter-from-class="transform scale-95 opacity-0" enter-to-class="transform scale-100 opacity-100"
                        leave-active-class="transition duration-75 ease-in"
                        leave-from-class="transform scale-100 opacity-100"
                        leave-to-class="transform scale-95 opacity-0">
                        <MenuItems class="action-menu">
                            <MenuItem v-if="!chore.is_completed" v-slot="{ active }">
                            <button :class="['menu-item', { 'active': active }]" @click.stop="toggleTimer">
                                <BaseIcon
                                    :name="isActiveTimer ? 'heroicons:pause-circle-20-solid' : 'heroicons:play-circle-20-solid'" />
                                <span>{{ isActiveTimer ? 'Stop Timer' : 'Start Timer' }}</span>
                            </button>
                            </MenuItem>
                            <MenuItem v-slot="{ active }">
                            <button :class="['menu-item', { 'active': active }]"
                                @click.stop="emit('open-history', chore)">
                                <BaseIcon name="heroicons:clock-20-solid" />
                                <span>View History</span>
                            </button>
                            </MenuItem>
                            <MenuItem v-slot="{ active }">
                            <button :class="['menu-item', { 'active': active }]" @click.stop="emit('edit', chore)">
                                <BaseIcon name="heroicons:pencil-20-solid" />
                                <span>Edit</span>
                            </button>
                            </MenuItem>
                            <MenuItem v-slot="{ active }">
                            <button :class="['menu-item', 'danger', { 'active': active }]"
                                @click.stop="emit('delete', chore)">
                                <BaseIcon name="heroicons:trash-20-solid" />
                                <span>Delete</span>
                            </button>
                            </MenuItem>
                        </MenuItems>
                    </transition>
                </Menu>
            </div>
        </div>

        <!-- Recursive children -->
        <ul v-if="chore.child_chores?.length" class="child-chores-list">
            <ChoreItem v-for="child in chore.child_chores" :key="child.id" :chore="child" :time-entries="timeEntries"
                :active-timer="activeTimer" @toggle-completion="emit('toggle-completion', $event)"
                @edit="emit('edit', $event)" @delete="emit('delete', $event)"
                @open-details="emit('open-details', $event)" @open-history="emit('open-history', $event)"
                @start-timer="emit('start-timer', $event)"
                @stop-timer="(chore, timeEntryId) => emit('stop-timer', chore, timeEntryId)" />
        </ul>
    </Card>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, computed } from 'vue';
import { formatDistanceToNow, isToday, isPast } from 'date-fns';
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
import type { ChoreWithCompletion } from '@/types/chore';
import type { TimeEntry } from '@/types/time_entry';
import { formatDuration } from '@/utils/formatters';
import BaseIcon from './BaseIcon.vue';
import { Button, Card } from '@/components/ui';

// --- props & emits ---
const props = defineProps<{
    chore: ChoreWithCompletion;
    timeEntries: TimeEntry[];
    activeTimer: TimeEntry | null;
}>();

const emit = defineEmits<{
    (e: 'toggle-completion', chore: ChoreWithCompletion): void;
    (e: 'edit', chore: ChoreWithCompletion): void;
    (e: 'delete', chore: ChoreWithCompletion): void;
    (e: 'open-details', chore: ChoreWithCompletion): void;
    (e: 'open-history', chore: ChoreWithCompletion): void;
    (e: 'start-timer', chore: ChoreWithCompletion): void;
    (e: 'stop-timer', chore: ChoreWithCompletion, timeEntryId: number): void;
}>();

// --- computed helpers ---
const isActiveTimer = computed(() =>
    !!props.activeTimer && props.activeTimer.chore_assignment_id === props.chore.current_assignment_id,
);

const totalTime = computed(() =>
    props.timeEntries.reduce((acc, entry) => acc + (entry.duration_seconds || 0), 0),
);

const dueInText = computed(() => {
    if (!props.chore.next_due_date) return '';
    const dueDate = new Date(props.chore.next_due_date);
    if (isToday(dueDate)) return 'Today';
    return formatDistanceToNow(dueDate, { addSuffix: true });
});

const isOverdue = computed(() => getDueDateStatus(props.chore) === 'overdue');
const isDueToday = computed(() => getDueDateStatus(props.chore) === 'due-today');

// --- methods ---
function toggleTimer() {
    if (isActiveTimer.value) {
        emit('stop-timer', props.chore, props.activeTimer!.id);
    } else {
        emit('start-timer', props.chore);
    }
}

function getDueDateStatus(chore: ChoreWithCompletion) {
    if (chore.is_completed) return 'completed';

    if (!chore.next_due_date) return 'none';

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const dueDate = new Date(chore.next_due_date);
    dueDate.setHours(0, 0, 0, 0);

    if (isPast(dueDate) && !isToday(dueDate)) return 'overdue';
    if (isToday(dueDate)) return 'due-today';
    return 'upcoming';
}
</script>

<script lang="ts">
export default {
    name: 'ChoreItem'
}
</script>

<style scoped>
.chore-item {
    @apply transition-all duration-micro ease-micro;
}

.chore-item.is-updating {
    @apply opacity-50;
}

.chore-content {
    @apply flex items-start gap-4;
}

/* Checkbox */
.chore-checkbox {
    @apply pt-0.5;
}

.custom-checkbox {
    @apply h-5 w-5 rounded;
    @apply text-primary-600 bg-surface-primary border-border-secondary;
    @apply focus:ring-primary-500 focus:ring-offset-surface-primary;
    @apply transition-colors duration-micro;
}

.is-completed .custom-checkbox {
    @apply border-transparent bg-neutral-300 dark:bg-neutral-600;
}

/* Details */
.chore-details {
    @apply flex-1 cursor-pointer;
}

.details-header {
    @apply flex items-center gap-2 flex-wrap;
}

.chore-name {
    @apply font-semibold text-text-primary;
    @apply transition-colors duration-micro;
}

.is-completed .chore-name {
    @apply line-through text-text-tertiary;
}

.chore-badges {
    @apply flex items-center gap-2;
}

.badge {
    @apply text-xs font-medium px-2 py-0.5 rounded-full;
}

.type-badge {
    @apply bg-primary-100 text-primary-700 dark:bg-primary-900/50 dark:text-primary-300;
}

.overdue-badge {
    @apply bg-error-100 text-error-700 dark:bg-error-900/50 dark:text-error-300;
}

.due-today-badge {
    @apply bg-warning-100 text-warning-700 dark:bg-warning-900/50 dark:text-warning-300;
}

.chore-description {
    @apply text-sm text-text-secondary mt-1 line-clamp-2;
}

.details-footer {
    @apply flex items-center gap-4 text-xs text-text-secondary mt-2;
}

.due-date-text,
.time-tracked-text {
    @apply flex items-center gap-1;
}

/* Actions */
.chore-actions {
    @apply relative z-10;
}

.action-menu {
    @apply absolute right-0 mt-2 w-48 origin-top-right;
    @apply bg-surface-elevated rounded-md shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none;
}

.menu-item {
    @apply flex items-center w-full px-3 py-2 text-sm gap-3;
    @apply text-text-primary;
}

.menu-item.active {
    @apply bg-surface-hover;
}

.menu-item.danger {
    @apply text-error-600 dark:text-error-400;
}

.menu-item.danger.active {
    @apply bg-error-50 dark:bg-error-900/50;
}

/* Children */
.child-chores-list {
    @apply mt-4 pl-6 border-l-2 border-border-secondary;
}
</style>