<template>
    <div class="chores-list-container">
        <!-- Header -->
        <div class="chores-header">
            <Heading size="xl" class="text-neutral-900">Chores</Heading>
            <div class="header-actions">
                <Button variant="soft" color="primary" size="sm" @click="handleAddChore">
                    <template #icon-left>
                        <span class="material-icons text-lg">add_task</span>
                    </template>
                    Add Chore
                </Button>
            </div>
        </div>

        <!-- Chore Categories Tabs -->
        <TabGroup @change="handleTabChange" v-slot="{ selectedIndex }">
            <TabList class="chore-tabs">
                <Tab v-for="(category, index) in choreCategories" :key="category.id" v-slot="{ selected }"
                    class="chore-tab" :class="getTabClasses(category, selected)">
                    <div class="tab-content">
                        <span class="tab-icon" :class="getTabIconClasses(category)">
                            <span class="material-icons">{{ category.icon }}</span>
                        </span>
                        <div class="tab-info">
                            <span class="tab-title">{{ category.title }}</span>
                            <span v-if="category.count > 0" class="tab-count" :class="getTabCountClasses(category)">
                                {{ category.count }}
                            </span>
                        </div>
                    </div>
                </Tab>
            </TabList>

            <TabPanels class="chore-panels">
                <TabPanel v-for="category in choreCategories" :key="category.id" class="chore-panel">
                    <!-- Loading State -->
                    <div v-if="isLoading" class="loading-state">
                        <div v-for="n in 3" :key="n" class="chore-skeleton">
                            <div class="skeleton-icon animate-skeleton"></div>
                            <div class="skeleton-content">
                                <div class="skeleton-title animate-skeleton"></div>
                                <div class="skeleton-subtitle animate-skeleton"></div>
                            </div>
                            <div class="skeleton-action animate-skeleton"></div>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div v-else-if="getFilteredChores(category.id).length === 0" class="empty-state">
                        <div class="empty-icon">
                            <span class="material-icons">{{ getEmptyStateIcon(category.id) }}</span>
                        </div>
                        <h3 class="empty-title">{{ getEmptyStateTitle(category.id) }}</h3>
                        <p class="empty-description">{{ getEmptyStateDescription(category.id) }}</p>
                        <Button v-if="category.id !== 'archive'" variant="soft" color="primary" size="sm"
                            @click="handleAddChore">
                            {{ getEmptyStateAction(category.id) }}
                        </Button>
                    </div>

                    <!-- Chores List -->
                    <div v-else class="chores-grid">
                        <TransitionGroup name="chore-list" tag="div" class="chores-container">
                            <ChoreCard v-for="chore in getFilteredChores(category.id)" :key="chore.id" :chore="chore"
                                :category="category.id" @complete="handleCompleteChore" @claim="handleClaimChore"
                                @view-details="handleViewDetails" class="chore-card-item" />
                        </TransitionGroup>
                    </div>
                </TabPanel>
            </TabPanels>
        </TabGroup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { TabGroup, TabList, Tab, TabPanels, TabPanel } from '@headlessui/vue'
import { useChoreStore } from '@/stores/choreStore'
import { useAuthStore } from '@/stores/auth'
import { useNotificationStore } from '@/stores/notifications'
import Heading from '@/components/ui/Heading.vue'
import Button from '@/components/ui/Button.vue'
import ChoreCard from '@/components/ChoreCard.vue'

interface ChoreCategory {
    id: 'priority' | 'upcoming' | 'available' | 'archive'
    title: string
    icon: string
    count: number
    priority: number
}

interface Chore {
    id: string
    name: string
    description?: string
    dueDate: Date
    priority: 'urgent' | 'high' | 'medium' | 'low'
    assignedTo?: string
    points: number
    isComplete: boolean
    completedAt?: Date
    completedBy?: string
    isOverdue: boolean
    isAvailable: boolean
    estimatedDuration?: number
}

const choreStore = useChoreStore()
const authStore = useAuthStore()
const notificationStore = useNotificationStore()

const isLoading = ref(true)
const selectedCategory = ref<string>('priority')

// Computed chore categories with dynamic counts
const choreCategories = computed<ChoreCategory[]>(() => {
    const allChores = choreStore.allChores || []
    const userId = authStore.user?.id

    return [
        {
            id: 'priority',
            title: 'Priority',
            icon: 'priority_high',
            count: getPriorityChores().length,
            priority: 1
        },
        {
            id: 'upcoming',
            title: 'Upcoming',
            icon: 'schedule',
            count: getUpcomingChores().length,
            priority: 2
        },
        {
            id: 'available',
            title: 'Available',
            icon: 'volunteer_activism',
            count: getAvailableChores().length,
            priority: 3
        },
        {
            id: 'archive',
            title: 'Archive',
            icon: 'archive',
            count: getArchivedChores().length,
            priority: 4
        }
    ]
})

// Filter functions for each category
const getPriorityChores = (): Chore[] => {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

    return choreStore.allChores
        .filter(chore => !chore.isComplete)
        .filter(chore => {
            const dueDate = new Date(chore.dueDate)
            return dueDate <= today || chore.isOverdue
        })
        .sort((a, b) => {
            // Sort by: overdue first, then by due date
            if (a.isOverdue && !b.isOverdue) return -1
            if (!a.isOverdue && b.isOverdue) return 1
            return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
        })
}

const getUpcomingChores = (): Chore[] => {
    const now = new Date()
    const weekFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)

    return choreStore.allChores
        .filter(chore => !chore.isComplete && !chore.isOverdue)
        .filter(chore => {
            const dueDate = new Date(chore.dueDate)
            return dueDate > now && dueDate <= weekFromNow
        })
        .sort((a, b) => new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime())
}

const getAvailableChores = (): Chore[] => {
    return choreStore.allChores
        .filter(chore => !chore.isComplete && chore.isAvailable)
        .sort((a, b) => b.points - a.points) // Sort by points descending
}

const getArchivedChores = (): Chore[] => {
    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)

    return choreStore.allChores
        .filter(chore => chore.isComplete && chore.completedAt && new Date(chore.completedAt) >= sevenDaysAgo)
        .sort((a, b) => new Date(b.completedAt!).getTime() - new Date(a.completedAt!).getTime())
}

const getFilteredChores = (categoryId: string): Chore[] => {
    switch (categoryId) {
        case 'priority':
            return getPriorityChores()
        case 'upcoming':
            return getUpcomingChores()
        case 'available':
            return getAvailableChores()
        case 'archive':
            return getArchivedChores()
        default:
            return []
    }
}

// Tab styling functions
const getTabClasses = (category: ChoreCategory, selected: boolean) => {
    const baseClasses = 'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/50'

    if (selected) {
        if (category.id === 'priority' && category.count > 0) {
            return `${baseClasses} tab-selected tab-priority-active`
        }
        return `${baseClasses} tab-selected`
    }

    return `${baseClasses} tab-unselected`
}

const getTabIconClasses = (category: ChoreCategory) => {
    if (category.id === 'priority' && category.count > 0) {
        return 'tab-icon-priority'
    }
    return 'tab-icon-default'
}

const getTabCountClasses = (category: ChoreCategory) => {
    if (category.id === 'priority' && category.count > 0) {
        return 'tab-count-priority'
    }
    return 'tab-count-default'
}

// Empty state functions
const getEmptyStateIcon = (categoryId: string) => {
    const icons = {
        priority: 'check_circle',
        upcoming: 'event_available',
        available: 'volunteer_activism',
        archive: 'archive'
    }
    return icons[categoryId as keyof typeof icons] || 'check_circle'
}

const getEmptyStateTitle = (categoryId: string) => {
    const titles = {
        priority: 'All caught up!',
        upcoming: 'Nothing this week',
        available: 'No available chores',
        archive: 'No recent completions'
    }
    return titles[categoryId as keyof typeof titles] || 'Nothing here'
}

const getEmptyStateDescription = (categoryId: string) => {
    const descriptions = {
        priority: 'No urgent or overdue tasks. Great work!',
        upcoming: 'No chores scheduled for this week.',
        available: 'All chores are assigned or completed.',
        archive: 'Complete some chores to see them here.'
    }
    return descriptions[categoryId as keyof typeof descriptions] || ''
}

const getEmptyStateAction = (categoryId: string) => {
    const actions = {
        priority: 'Add New Chore',
        upcoming: 'Schedule Chore',
        available: 'Create Available Chore',
        archive: 'View All Chores'
    }
    return actions[categoryId as keyof typeof actions] || 'Add Chore'
}

// Event handlers
const handleTabChange = (index: number) => {
    const category = choreCategories.value[index]
    selectedCategory.value = category.id
}

const handleAddChore = () => {
    // Emit event or navigate to chore creation
    notificationStore.addNotification({
        type: 'info',
        message: 'Chore creation coming soon!',
    })
}

const handleCompleteChore = async (chore: Chore) => {
    try {
        await choreStore.completeChore(chore.id)

        // Add celebration notification
        notificationStore.addNotification({
            type: 'success',
            message: `🎉 "${chore.name}" completed! +${chore.points} points`,
        })

        // Haptic feedback if available
        if ('vibrate' in navigator) {
            navigator.vibrate([100, 50, 100])
        }
    } catch (error) {
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to complete chore. Please try again.',
        })
    }
}

const handleClaimChore = async (chore: Chore) => {
    try {
        await choreStore.claimChore(chore.id, authStore.user!.id)

        notificationStore.addNotification({
            type: 'success',
            message: `You claimed "${chore.name}"`,
        })
    } catch (error) {
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to claim chore. Please try again.',
        })
    }
}

const handleViewDetails = (chore: Chore) => {
    // Navigate to chore details or open modal
    notificationStore.addNotification({
        type: 'info',
        message: 'Chore details coming soon!',
    })
}

// Load chores on mount
onMounted(async () => {
    try {
        await choreStore.fetchChores()
    } catch (error) {
        console.error('Failed to load chores:', error)
    } finally {
        isLoading.value = false
    }
})
</script>

<style scoped>
.chores-list-container {
    @apply space-y-6;
}

.chores-header {
    @apply flex items-center justify-between;
}

.header-actions {
    @apply flex items-center gap-3;
}

/* Tab Styles */
.chore-tabs {
    @apply flex bg-neutral-100 rounded-xl p-1 mb-6;
    @apply overflow-x-auto scrollbar-hide;
}

.chore-tab {
    @apply flex-1 min-w-0 px-4 py-3 rounded-lg transition-all duration-micro;
    @apply cursor-pointer;
}

.tab-selected {
    @apply bg-white shadow-soft;
}

.tab-unselected {
    @apply hover:bg-white/50;
}

.tab-priority-active {
    @apply bg-error-50 border border-error-200;
}

.tab-content {
    @apply flex items-center gap-3;
}

.tab-icon {
    @apply flex-shrink-0;
}

.tab-icon-default {
    @apply text-neutral-600;
}

.tab-icon-priority {
    @apply text-error-500;
}

.tab-info {
    @apply flex-1 min-w-0 flex items-center justify-between;
}

.tab-title {
    @apply text-sm font-medium text-neutral-900 truncate;
}

.tab-count {
    @apply text-xs px-2 py-1 rounded-full font-medium;
}

.tab-count-default {
    @apply bg-neutral-200 text-neutral-700;
}

.tab-count-priority {
    @apply bg-error-100 text-error-700;
}

/* Panel Styles */
.chore-panels {
    @apply space-y-4;
}

.chore-panel {
    @apply focus:outline-none;
}

/* Loading State */
.loading-state {
    @apply space-y-4;
}

.chore-skeleton {
    @apply flex items-center gap-4 p-4 bg-white rounded-lg border border-neutral-200;
}

.skeleton-icon {
    @apply w-10 h-10 bg-neutral-200 rounded-full;
}

.skeleton-content {
    @apply flex-1 space-y-2;
}

.skeleton-title {
    @apply h-4 bg-neutral-200 rounded w-3/4;
}

.skeleton-subtitle {
    @apply h-3 bg-neutral-200 rounded w-1/2;
}

.skeleton-action {
    @apply w-20 h-8 bg-neutral-200 rounded;
}

/* Empty State */
.empty-state {
    @apply text-center py-12 px-4;
}

.empty-icon {
    @apply text-neutral-400 text-5xl mb-4;
}

.empty-title {
    @apply text-lg font-medium text-neutral-900 mb-2;
}

.empty-description {
    @apply text-sm text-neutral-600 mb-6 max-w-md mx-auto;
}

/* Chores Grid */
.chores-grid {
    @apply space-y-3;
}

.chores-container {
    @apply space-y-3;
}

.chore-card-item {
    @apply transition-all duration-micro;
}

/* Animations */
.chore-list-enter-active,
.chore-list-leave-active {
    transition: all 300ms ease-page;
}

.chore-list-enter-from {
    opacity: 0;
    transform: translateY(20px) scale(0.95);
}

.chore-list-leave-to {
    opacity: 0;
    transform: translateX(-20px) scale(0.95);
}

.chore-list-move {
    transition: transform 300ms ease-page;
}

/* Mobile Optimizations */
@media (max-width: 640px) {
    .chore-tabs {
        @apply mb-4;
    }

    .tab-content {
        @apply gap-2;
    }

    .tab-title {
        @apply text-xs;
    }

    .tab-count {
        @apply text-xs px-1.5 py-0.5;
    }

    .empty-state {
        @apply py-8;
    }

    .empty-icon {
        @apply text-4xl mb-3;
    }

    .empty-title {
        @apply text-base;
    }
}

/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {

    .chore-list-enter-active,
    .chore-list-leave-active,
    .chore-list-move {
        transition: none;
    }

    .chore-card-item {
        transition: none;
    }
}
</style>