<template>
    <main class="container page-padding">
        <div class="page-header">
            <h1 class="mb-3">{{ $t('myChoresPage.title') }}</h1>
            <div class="header-controls">
                <label class="toggle-switch">
                    <input type="checkbox" v-model="showCompleted" @change="loadAssignments">
                    <span class="toggle-slider"></span>
                    {{ $t('myChoresPage.showCompletedToggle') }}
                </label>
            </div>
        </div>

        <!-- My Assignments Timeline -->
        <div v-if="assignments.length > 0" class="assignments-timeline">
            <!-- Overdue Section -->
            <div v-if="assignmentsByTimeline.overdue.length > 0" class="timeline-section overdue">
                <div class="timeline-header">
                    <div class="timeline-dot overdue"></div>
                    <h2 class="timeline-title">{{ $t('myChoresPage.timelineHeaders.overdue') }}</h2>
                    <span class="timeline-count">{{ assignmentsByTimeline.overdue.length }}</span>
                </div>
                <div class="timeline-items">
                    <div v-for="assignment in assignmentsByTimeline.overdue" :key="assignment.id"
                        class="timeline-assignment-card overdue">
                        <div class="assignment-timeline-marker"></div>
                        <div class="assignment-content">
                            <div class="assignment-header">
                                <h3>{{ assignment.chore?.name }}</h3>
                                <div class="assignment-tags">
                                    <span class="chore-type-tag" :class="assignment.chore?.type">
                                        {{ assignment.chore?.type === 'personal' ? $t('myChoresPage.choreCard.personal') : $t('myChoresPage.choreCard.group') }}
                                    </span>
                                    <span class="chore-frequency-tag" :class="assignment.chore?.frequency">
                                        {{ formatFrequency(assignment.chore?.frequency) }}
                                    </span>
                                </div>
                            </div>
                            <div class="assignment-meta">
                                <div class="assignment-due-date overdue">
                                    <span class="material-icons">schedule</span>
                                    {{ $t('myChoresPage.choreCard.duePrefix') }} {{ formatDate(assignment.due_date) }}
                                </div>
                                <div v-if="assignment.chore?.description" class="assignment-description">
                                    {{ assignment.chore.description }}
                                </div>
                            </div>
                            <div class="assignment-actions">
                                <button class="btn btn-success btn-sm" @click="completeAssignment(assignment)"
                                    :disabled="isCompleting">
                                    <span class="material-icons">check_circle</span>
                                    {{ $t('myChoresPage.choreCard.markCompleteButton') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Today Section -->
            <div v-if="assignmentsByTimeline.today.length > 0" class="timeline-section today">
                <div class="timeline-header">
                    <div class="timeline-dot today"></div>
                    <h2 class="timeline-title">{{ $t('myChoresPage.timelineHeaders.today') }}</h2>
                    <span class="timeline-count">{{ assignmentsByTimeline.today.length }}</span>
                </div>
                <div class="timeline-items">
                    <div v-for="assignment in assignmentsByTimeline.today" :key="assignment.id"
                        class="timeline-assignment-card today">
                        <div class="assignment-timeline-marker"></div>
                        <div class="assignment-content">
                            <div class="assignment-header">
                                <h3>{{ assignment.chore?.name }}</h3>
                                <div class="assignment-tags">
                                    <span class="chore-type-tag" :class="assignment.chore?.type">
                                        {{ assignment.chore?.type === 'personal' ? $t('myChoresPage.choreCard.personal') : $t('myChoresPage.choreCard.group') }}
                                    </span>
                                    <span class="chore-frequency-tag" :class="assignment.chore?.frequency">
                                        {{ formatFrequency(assignment.chore?.frequency) }}
                                    </span>
                                </div>
                            </div>
                            <div class="assignment-meta">
                                <div class="assignment-due-date today">
                                    <span class="material-icons">today</span>
                                    {{ $t('myChoresPage.choreCard.dueToday') }}
                                </div>
                                <div v-if="assignment.chore?.description" class="assignment-description">
                                    {{ assignment.chore.description }}
                                </div>
                            </div>
                            <div class="assignment-actions">
                                <button class="btn btn-success btn-sm" @click="completeAssignment(assignment)"
                                    :disabled="isCompleting">
                                    <span class="material-icons">check_circle</span>
                                    {{ $t('myChoresPage.choreCard.markCompleteButton') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- This Week Section -->
            <div v-if="assignmentsByTimeline.thisWeek.length > 0" class="timeline-section this-week">
                <div class="timeline-header">
                    <div class="timeline-dot this-week"></div>
                    <h2 class="timeline-title">{{ $t('myChoresPage.timelineHeaders.thisWeek') }}</h2>
                    <span class="timeline-count">{{ assignmentsByTimeline.thisWeek.length }}</span>
                </div>
                <div class="timeline-items">
                    <div v-for="assignment in assignmentsByTimeline.thisWeek" :key="assignment.id"
                        class="timeline-assignment-card this-week">
                        <div class="assignment-timeline-marker"></div>
                        <div class="assignment-content">
                            <div class="assignment-header">
                                <h3>{{ assignment.chore?.name }}</h3>
                                <div class="assignment-tags">
                                    <span class="chore-type-tag" :class="assignment.chore?.type">
                                        {{ assignment.chore?.type === 'personal' ? $t('myChoresPage.choreCard.personal') : $t('myChoresPage.choreCard.group') }}
                                    </span>
                                    <span class="chore-frequency-tag" :class="assignment.chore?.frequency">
                                        {{ formatFrequency(assignment.chore?.frequency) }}
                                    </span>
                                </div>
                            </div>
                            <div class="assignment-meta">
                                <div class="assignment-due-date this-week">
                                    <span class="material-icons">date_range</span>
                                    {{ $t('myChoresPage.choreCard.duePrefix') }} {{ formatDate(assignment.due_date) }}
                                </div>
                                <div v-if="assignment.chore?.description" class="assignment-description">
                                    {{ assignment.chore.description }}
                                </div>
                            </div>
                            <div class="assignment-actions">
                                <button class="btn btn-success btn-sm" @click="completeAssignment(assignment)"
                                    :disabled="isCompleting">
                                    <span class="material-icons">check_circle</span>
                                    {{ $t('myChoresPage.choreCard.markCompleteButton') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Later Section -->
            <div v-if="assignmentsByTimeline.later.length > 0" class="timeline-section later">
                <div class="timeline-header">
                    <div class="timeline-dot later"></div>
                    <h2 class="timeline-title">{{ $t('myChoresPage.timelineHeaders.later') }}</h2>
                    <span class="timeline-count">{{ assignmentsByTimeline.later.length }}</span>
                </div>
                <div class="timeline-items">
                    <div v-for="assignment in assignmentsByTimeline.later" :key="assignment.id"
                        class="timeline-assignment-card later">
                        <div class="assignment-timeline-marker"></div>
                        <div class="assignment-content">
                            <div class="assignment-header">
                                <h3>{{ assignment.chore?.name }}</h3>
                                <div class="assignment-tags">
                                    <span class="chore-type-tag" :class="assignment.chore?.type">
                                        {{ assignment.chore?.type === 'personal' ? $t('myChoresPage.choreCard.personal') : $t('myChoresPage.choreCard.group') }}
                                    </span>
                                    <span class="chore-frequency-tag" :class="assignment.chore?.frequency">
                                        {{ formatFrequency(assignment.chore?.frequency) }}
                                    </span>
                                </div>
                            </div>
                            <div class="assignment-meta">
                                <div class="assignment-due-date later">
                                    <span class="material-icons">schedule</span>
                                    {{ $t('myChoresPage.choreCard.duePrefix') }} {{ formatDate(assignment.due_date) }}
                                </div>
                                <div v-if="assignment.chore?.description" class="assignment-description">
                                    {{ assignment.chore.description }}
                                </div>
                            </div>
                            <div class="assignment-actions">
                                <button class="btn btn-success btn-sm" @click="completeAssignment(assignment)"
                                    :disabled="isCompleting">
                                    <span class="material-icons">check_circle</span>
                                    {{ $t('myChoresPage.choreCard.markCompleteButton') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Completed Section (if showing completed) -->
            <div v-if="showCompleted && assignmentsByTimeline.completed.length > 0" class="timeline-section completed">
                <div class="timeline-header">
                    <div class="timeline-dot completed"></div>
                    <h2 class="timeline-title">{{ $t('myChoresPage.timelineHeaders.completed') }}</h2>
                    <span class="timeline-count">{{ assignmentsByTimeline.completed.length }}</span>
                </div>
                <div class="timeline-items">
                    <div v-for="assignment in assignmentsByTimeline.completed" :key="assignment.id"
                        class="timeline-assignment-card completed">
                        <div class="assignment-timeline-marker"></div>
                        <div class="assignment-content">
                            <div class="assignment-header">
                                <h3>{{ assignment.chore?.name }}</h3>
                                <div class="assignment-tags">
                                    <span class="chore-type-tag" :class="assignment.chore?.type">
                                        {{ assignment.chore?.type === 'personal' ? $t('myChoresPage.choreCard.personal') : $t('myChoresPage.choreCard.group') }}
                                    </span>
                                    <span class="chore-frequency-tag" :class="assignment.chore?.frequency">
                                        {{ formatFrequency(assignment.chore?.frequency) }}
                                    </span>
                                </div>
                            </div>
                            <div class="assignment-meta">
                                <div class="assignment-due-date completed">
                                    <span class="material-icons">check_circle</span>
                                    {{ $t('myChoresPage.choreCard.completedPrefix') }} {{ formatDate(assignment.completed_at || assignment.updated_at) }}
                                </div>
                                <div v-if="assignment.chore?.description" class="assignment-description">
                                    {{ assignment.chore.description }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-else class="card empty-state-card">
            <svg class="icon icon-lg" aria-hidden="true">
                <use xlink:href="#icon-clipboard" />
            </svg>
            <h3>{{ $t('myChoresPage.emptyState.title') }}</h3>
            <p v-if="showCompleted">{{ $t('myChoresPage.emptyState.noAssignmentsAll') }}</p>
            <p v-else>{{ $t('myChoresPage.emptyState.noAssignmentsPending') }}</p>
            <router-link to="/chores" class="btn btn-primary mt-2">
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-eye" />
                </svg>
                {{ $t('myChoresPage.emptyState.viewAllChoresButton') }}
            </router-link>
        </div>
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { format } from 'date-fns'
import { choreService } from '../services/choreService'
import { useNotificationStore } from '../stores/notifications'
import type { ChoreAssignment, ChoreFrequency } from '../types/chore'

const { t } = useI18n()
const notificationStore = useNotificationStore()

// State
const assignments = ref<ChoreAssignment[]>([])
const showCompleted = ref(false)
const isCompleting = ref(false)

// Computed property for timeline grouping
const assignmentsByTimeline = computed(() => {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    const nextWeek = new Date(today)
    nextWeek.setDate(nextWeek.getDate() + 7)

    const timeline = {
        overdue: [] as ChoreAssignment[],
        today: [] as ChoreAssignment[],
        thisWeek: [] as ChoreAssignment[],
        later: [] as ChoreAssignment[],
        completed: [] as ChoreAssignment[]
    }

    assignments.value.forEach(assignment => {
        if (assignment.is_complete) {
            timeline.completed.push(assignment)
            return
        }

        const dueDate = new Date(assignment.due_date)
        const assignmentDate = new Date(dueDate.getFullYear(), dueDate.getMonth(), dueDate.getDate())

        if (assignmentDate < today) {
            timeline.overdue.push(assignment)
        } else if (assignmentDate.getTime() === today.getTime()) {
            timeline.today.push(assignment)
        } else if (assignmentDate < nextWeek) {
            timeline.thisWeek.push(assignment)
        } else {
            timeline.later.push(assignment)
        }
    })

    // Sort each timeline section
    Object.values(timeline).forEach(section => {
        section.sort((a, b) => {
            const dateA = new Date(a.due_date)
            const dateB = new Date(b.due_date)
            if (dateA.getTime() !== dateB.getTime()) {
                return dateA.getTime() - dateB.getTime()
            }
            return (a.chore?.name || '').localeCompare(b.chore?.name || '')
        })
    })

    return timeline
})

// frequencyOptions is not directly used for display labels anymore, but can be kept for logic if needed elsewhere.
// const frequencyOptions = [
//     { label: 'One Time', value: 'one_time' as ChoreFrequency },
//     { label: 'Daily', value: 'daily' as ChoreFrequency },
//     { label: 'Weekly', value: 'weekly' as ChoreFrequency },
//     { label: 'Monthly', value: 'monthly' as ChoreFrequency },
//     { label: 'Custom', value: 'custom' as ChoreFrequency }
// ]

// Methods
const loadAssignments = async () => {
    try {
        assignments.value = await choreService.getMyAssignments(showCompleted.value)
    } catch (error) {
        console.error('Failed to load assignments:', error)
        notificationStore.addNotification({
            message: t('myChoresPage.notifications.loadFailed'),
            type: 'error'
        })
    }
}

const completeAssignment = async (assignment: ChoreAssignment) => {
    if (isCompleting.value) return

    isCompleting.value = true
    try {
        await choreService.completeAssignment(assignment.id)
        notificationStore.addNotification({
            message: t('myChoresPage.notifications.markedComplete', { choreName: assignment.chore?.name || '' }),
            type: 'success'
        })
        // Reload assignments to show updated state
        await loadAssignments()
    } catch (error) {
        console.error('Failed to complete assignment:', error)
        notificationStore.addNotification({
            message: t('myChoresPage.notifications.markCompleteFailed'),
            type: 'error'
        })
    } finally {
        isCompleting.value = false
    }
}

const formatDate = (date: string | undefined) => {
    if (!date) return t('myChoresPage.dates.unknownDate');

    // Attempt to parse and format; date-fns handles various ISO and other formats.
    try {
        const parsedDate = new Date(date);
        // Check if parsedDate is valid
        if (isNaN(parsedDate.getTime())) {
            // Handle cases like "YYYY-MM-DD" which might be parsed as UTC midnight
            // and then potentially displayed incorrectly depending on timezone.
            // If the input is just a date string without time, ensure it's treated as local.
            if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
                 const [year, month, day] = date.split('-').map(Number);
                 return format(new Date(year, month - 1, day), 'MMM d, yyyy');
            }
            return t('myChoresPage.dates.invalidDate');
        }
        return format(parsedDate, 'MMM d, yyyy');
    } catch (e) {
        // Catch any error during parsing (though Date constructor is quite forgiving)
        return t('myChoresPage.dates.invalidDate');
    }
}

const formatFrequency = (frequency: ChoreFrequency | undefined) => {
    if (!frequency) return t('myChoresPage.frequencies.unknown');
    // Assuming keys like myChoresPage.frequencies.one_time, myChoresPage.frequencies.daily
    // The ChoreFrequency enum values ('one_time', 'daily', etc.) match the last part of the key.
    return t(`myChoresPage.frequencies.${frequency}`);
}

// Lifecycle
onMounted(() => {
    loadAssignments()
})
</script>

<style scoped>
.page-padding {
    padding: 1rem;
    max-width: 800px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;
}

.header-controls {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.toggle-switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
    cursor: pointer;
    user-select: none;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    border-radius: 34px;
    transition: 0.4s;
    border: 2px solid #111;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 4px;
    bottom: 4px;
    background-color: #111;
    border-radius: 50%;
    transition: 0.4s;
}

input:checked+.toggle-slider {
    background-color: #007bff;
}

input:checked+.toggle-slider:before {
    transform: translateX(26px);
    background-color: white;
}

.mb-3 {
    margin-bottom: 1.5rem;
}

.mt-2 {
    margin-top: 1rem;
}

/* Timeline Layout */
.assignments-timeline {
    position: relative;
    margin-left: 2rem;
}

/* Timeline line */
.assignments-timeline::before {
    content: '';
    position: absolute;
    left: -1rem;
    top: 0;
    bottom: 0;
    width: 4px;
    background: #ddd;
    border-radius: 2px;
}

/* Timeline Sections */
.timeline-section {
    position: relative;
    margin-bottom: 2rem;
    background: var(--light);
    border-radius: 18px;
    box-shadow: 6px 6px 0 #111;
    border: 3px solid #111;
    overflow: hidden;
}

.timeline-section.overdue {
    border-color: #dc3545;
    box-shadow: 6px 6px 0 #dc3545;
}

.timeline-section.today {
    border-color: #007bff;
    box-shadow: 6px 6px 0 #007bff;
}

.timeline-section.this-week {
    border-color: #28a745;
    box-shadow: 6px 6px 0 #28a745;
}

.timeline-section.later {
    border-color: #6c757d;
    box-shadow: 6px 6px 0 #6c757d;
}

.timeline-section.completed {
    border-color: #28a745;
    box-shadow: 6px 6px 0 #28a745;
    opacity: 0.8;
}

/* Timeline Header */
.timeline-header {
    padding: 1.5rem;
    border-bottom: 3px solid;
    background: #fafafa;
    display: flex;
    align-items: center;
    gap: 1rem;
}

.timeline-dot {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 3px solid #111;
    background: white;
    position: relative;
    z-index: 2;
}

.timeline-dot.overdue {
    background: #dc3545;
    border-color: #dc3545;
}

.timeline-dot.today {
    background: #007bff;
    border-color: #007bff;
}

.timeline-dot.this-week {
    background: #28a745;
    border-color: #28a745;
}

.timeline-dot.later {
    background: #6c757d;
    border-color: #6c757d;
}

.timeline-dot.completed {
    background: #28a745;
    border-color: #28a745;
}

.timeline-title {
    font-size: 1.25rem;
    font-weight: 700;
    margin: 0;
    color: #111;
}

.timeline-count {
    background: #111;
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 12px;
    font-size: 0.875rem;
    font-weight: 600;
    margin-left: auto;
}

/* Assignment Cards */
.timeline-assignment-card {
    position: relative;
    padding: 1.5rem;
    border-bottom: 2px solid #eee;
    background: white;
    transition: all 0.2s;
}

.timeline-assignment-card:hover {
    background: #f8f9fa;
}

.timeline-assignment-card:last-child {
    border-bottom: none;
}

.assignment-timeline-marker {
    position: absolute;
    left: -2.4rem;
    top: 1.5rem;
    width: 12px;
    height: 12px;
    background: #111;
    border-radius: 50%;
    border: 3px solid white;
    z-index: 1;
}

.assignment-content {
    padding-left: 0.5rem;
}

.assignment-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1rem;
}

.assignment-header h3 {
    margin: 0;
    font-size: 1.125rem;
    font-weight: 600;
    color: #111;
}

.assignment-tags {
    display: flex;
    gap: 0.5rem;
    flex-shrink: 0;
    margin-left: 1rem;
}

.chore-type-tag,
.chore-frequency-tag {
    padding: 0.25rem 0.75rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
    border: 2px solid;
}

.chore-type-tag.personal {
    background: #e3f2fd;
    color: #1976d2;
    border-color: #1976d2;
}

.chore-type-tag.group {
    background: #f3e5f5;
    color: #7b1fa2;
    border-color: #7b1fa2;
}

.chore-frequency-tag {
    background: #f5f5f5;
    color: #666;
    border-color: #ddd;
}

.assignment-meta {
    margin-bottom: 1rem;
}

.assignment-due-date {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.assignment-due-date.overdue {
    color: #dc3545;
}

.assignment-due-date.today {
    color: #007bff;
}

.assignment-due-date.this-week {
    color: #28a745;
}

.assignment-due-date.later {
    color: #6c757d;
}

.assignment-due-date.completed {
    color: #28a745;
}

.assignment-description {
    color: #666;
    font-size: 0.875rem;
    line-height: 1.4;
}

.assignment-actions {
    display: flex;
    gap: 0.75rem;
}

.btn {
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all 0.2s;
    text-decoration: none;
    border: 2px solid;
    font-size: 0.875rem;
}

.btn-sm {
    padding: 0.375rem 0.75rem;
    font-size: 0.8125rem;
}

.btn-success {
    background: #28a745;
    color: white;
    border-color: #28a745;
}

.btn-success:hover:not(:disabled) {
    background: #218838;
    border-color: #218838;
}

.btn-primary {
    background: #111;
    color: white;
    border-color: #111;
}

.btn-primary:hover {
    background: #333;
    border-color: #333;
}

.btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.card {
    background: white;
    border: 3px solid #111;
    border-radius: 18px;
    box-shadow: 6px 6px 0 #111;
    overflow: hidden;
}

.empty-state-card {
    text-align: center;
    padding: 3rem 2rem;
}

.empty-state-card .icon-lg {
    width: 4rem;
    height: 4rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.empty-state-card h3 {
    margin: 0 0 1rem 0;
    color: #111;
}

.empty-state-card p {
    margin: 0 0 1rem 0;
    color: #666;
}
</style>