<template>
    <Card variant="soft" color="primary" padding="lg" class="quick-win-suggestion">
        <!-- Loading State -->
        <div v-if="isLoading" class="suggestion-loading">
            <Spinner size="sm" />
            <span class="loading-text">Finding your next quick win...</span>
        </div>

        <!-- Suggestion Content -->
        <div v-else-if="currentSuggestion" class="suggestion-content">
            <!-- Suggestion Header -->
            <div class="suggestion-header">
                <div class="suggestion-icon">
                    <BaseIcon :name="getSuggestionIconName(currentSuggestion.icon)" :class="iconVariantClasses" />
                </div>
                <div class="suggestion-meta">
                    <span class="suggestion-type">{{ currentSuggestion.type }}</span>
                    <span class="suggestion-points">+{{ currentSuggestion.points }} points</span>
                </div>
            </div>

            <!-- Suggestion Body -->
            <div class="suggestion-body">
                <h3 class="suggestion-title">{{ currentSuggestion.title }}</h3>
                <p class="suggestion-description">{{ currentSuggestion.description }}</p>

                <!-- Context Information -->
                <div v-if="currentSuggestion.context" class="suggestion-context">
                    <span class="context-indicator">
                        <BaseIcon name="heroicons:information-circle-20-solid" class="context-icon" />
                        {{ currentSuggestion.context }}
                    </span>
                </div>
            </div>

            <!-- Suggestion Actions -->
            <div class="suggestion-actions">
                <Button :variant="currentSuggestion.priority === 'high' ? 'solid' : 'outline'" :color="actionColor"
                    size="sm" fullWidth @click="handleTakeAction" :loading="isActioning" class="primary-action">
                    <template #icon-left>
                        <BaseIcon :name="getSuggestionIconName(currentSuggestion.actionIcon)" />
                    </template>
                    {{ currentSuggestion.actionText }}
                </Button>

                <Button variant="ghost" color="neutral" size="sm" @click="handleDismiss" class="dismiss-btn">
                    <template #icon-left>
                        <BaseIcon name="heroicons:x-mark-20-solid" />
                    </template>
                    Dismiss
                </Button>
            </div>
        </div>

        <!-- Empty State -->
        <div v-else class="suggestion-empty">
            <div class="empty-icon">
                <BaseIcon name="heroicons:trophy-20-solid" class="trophy-icon" />
            </div>
            <h3 class="empty-title">All caught up!</h3>
            <p class="empty-description">No immediate suggestions right now. Check back later for new opportunities.</p>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useChoreStore } from '@/stores/choreStore'
import { useListsStore } from '@/stores/listsStore'
import { useNotificationStore } from '@/stores/notifications'
import { Card, Button, Spinner } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'

interface Suggestion {
    id: string
    type: 'Chore' | 'Shopping' | 'Expense' | 'Organization'
    priority: 'high' | 'medium' | 'low'
    title: string
    description: string
    context?: string
    icon: string
    actionIcon: string
    actionText: string
    points: number
    action: () => void | Promise<void>
    target?: any // The target item/chore/etc for the action
}

const router = useRouter()
const authStore = useAuthStore()
const choreStore = useChoreStore()
const listsStore = useListsStore()
const notificationStore = useNotificationStore()

const isLoading = ref(true)
const isActioning = ref(false)
const currentSuggestion = ref<Suggestion | null>(null)
const suggestionHistory = ref<Set<string>>(new Set())
const refreshInterval = ref<number | null>(null)

// Enhanced icon mapping for better visual consistency
const getSuggestionIconName = (materialIcon: string): string => {
    const iconMap: Record<string, string> = {
        'warning': 'heroicons:exclamation-triangle-20-solid',
        'today': 'heroicons:calendar-20-solid',
        'star': 'heroicons:star-20-solid',
        'shopping_cart': 'heroicons:shopping-cart-20-solid',
        'schedule': 'heroicons:clock-20-solid',
        'check_circle': 'heroicons:check-circle-20-solid',
        'play_arrow': 'heroicons:play-20-solid',
        'volunteer_activism': 'heroicons:hand-raised-20-solid',
        'store': 'heroicons:building-storefront-20-solid',
        'calendar_view_day': 'heroicons:calendar-days-20-solid',
        'emoji_events': 'heroicons:trophy-20-solid',
        'lightbulb': 'heroicons:light-bulb-20-solid',
        'target': 'heroicons:cursor-arrow-rays-20-solid',
        'flash_on': 'heroicons:bolt-20-solid',
        'trending_up': 'heroicons:arrow-trending-up-20-solid'
    }
    return iconMap[materialIcon] || 'heroicons:sparkles-20-solid'
}

// Enhanced color scheme based on priority and type
const iconVariantClasses = computed(() => {
    if (!currentSuggestion.value) return ''
    const { priority, type } = currentSuggestion.value

    if (priority === 'high') return 'text-error-600 dark:text-error-400'
    if (type === 'Chore') return 'text-primary-600 dark:text-primary-400'
    if (type === 'Shopping') return 'text-success-600 dark:text-success-400'
    if (type === 'Expense') return 'text-warning-600 dark:text-warning-400'
    return 'text-text-secondary'
})

const actionColor = computed(() => {
    if (!currentSuggestion.value) return 'primary'
    const { priority } = currentSuggestion.value

    if (priority === 'high') return 'error'
    return 'primary'
})

// Generate intelligent suggestions based on user data and patterns
const generateSuggestions = (): Suggestion[] => {
    const suggestions: Suggestion[] = []
    const now = new Date()
    const user = authStore.user

    if (!user) return suggestions

    // 1. OVERDUE CHORES (Highest Priority)
    const allChores = choreStore.allChores
    const overdueChores = allChores.filter((chore: any) => {
        if (!chore.assignments || chore.assignments.length === 0) return false
        const latestAssignment = chore.assignments[chore.assignments.length - 1]
        if (latestAssignment.is_complete) return false
        const dueDate = new Date(latestAssignment.due_date)
        return dueDate < now
    })

    if (overdueChores.length > 0) {
        const urgentChore = overdueChores[0]
        const assignment = urgentChore.assignments[urgentChore.assignments.length - 1]
        const daysOverdue = Math.ceil((now.getTime() - new Date(assignment.due_date).getTime()) / (1000 * 60 * 60 * 24))

        suggestions.push({
            id: `overdue-chore-${urgentChore.id}`,
            type: 'Chore',
            priority: 'high',
            title: `Complete "${urgentChore.name}"`,
            description: 'This task is overdue and may be blocking others.',
            context: `Overdue by ${daysOverdue} days`,
            icon: 'warning',
            actionIcon: 'check_circle',
            actionText: 'Complete Now',
            points: 20, // High priority bonus
            action: () => handleCompleteChore(urgentChore, assignment),
            target: urgentChore
        })
    }

    // 2. DUE TODAY CHORES
    const dueTodayChores = allChores.filter((chore: any) => {
        if (!chore.assignments || chore.assignments.length === 0) return false
        const latestAssignment = chore.assignments[chore.assignments.length - 1]
        if (latestAssignment.is_complete) return false
        const dueDate = new Date(latestAssignment.due_date)
        return dueDate.toDateString() === now.toDateString()
    })

    if (dueTodayChores.length > 0) {
        const todayChore = dueTodayChores[0]
        const assignment = todayChore.assignments[todayChore.assignments.length - 1]

        suggestions.push({
            id: `due-today-${todayChore.id}`,
            type: 'Chore',
            priority: 'medium',
            title: `Tackle "${todayChore.name}"`,
            description: 'Due today - perfect time to get it done!',
            icon: 'today',
            actionIcon: 'play_arrow',
            actionText: 'Start Task',
            points: 10,
            action: () => handleCompleteChore(todayChore, assignment),
            target: todayChore
        })
    }

    // 3. AVAILABLE HIGH-POINT CHORES
    const availableChores = allChores.filter((chore: any) => {
        if (!chore.assignments || chore.assignments.length === 0) return true // Can be claimed
        const latestAssignment = chore.assignments[chore.assignments.length - 1]
        return !latestAssignment.is_complete
    })

    if (availableChores.length > 0) {
        const highValueChore = availableChores[0]

        suggestions.push({
            id: `high-value-${highValueChore.id}`,
            type: 'Chore',
            priority: 'medium',
            title: `Earn big with "${highValueChore.name}"`,
            description: 'High-value task available for quick points!',
            icon: 'star',
            actionIcon: 'target',
            actionText: 'Claim Task',
            points: 15,
            action: () => { router.push('/chores') },
            target: highValueChore
        })
    }

    // 4. SHOPPING OPTIMIZATION (simplified for current list)
    const currentList = listsStore.currentList
    if (currentList && currentList.items) {
        const pendingItems = currentList.items.filter((item: any) => !item.is_complete && !item.claimed_by_user_id)

        if (pendingItems.length >= 3) {
            suggestions.push({
                id: `shopping-${currentList.id}`,
                type: 'Shopping',
                priority: 'medium',
                title: 'Complete shopping trip',
                description: `${pendingItems.length} items waiting on "${currentList.name}"`,
                icon: 'shopping_cart',
                actionIcon: 'check_circle',
                actionText: 'Shop Now',
                points: Math.min(pendingItems.length * 2, 20),
                action: () => { router.push(`/lists/${currentList.id}`) },
                target: currentList
            })
        }
    }

    // 5. QUICK WINS BASED ON TIME
    const hour = now.getHours()
    if (hour >= 7 && hour <= 10) {
        // Morning suggestions
        suggestions.push({
            id: 'morning-routine',
            type: 'Organization',
            priority: 'low',
            title: 'Start strong today',
            description: 'Morning energy is perfect for quick organization tasks',
            icon: 'lightbulb',
            actionIcon: 'flash_on',
            actionText: 'Get Organized',
            points: 5,
            action: () => { router.push('/chores?filter=quick') }
        })
    } else if (hour >= 18 && hour <= 21) {
        // Evening wind-down
        suggestions.push({
            id: 'evening-prep',
            type: 'Organization',
            priority: 'low',
            title: 'Prep for tomorrow',
            description: 'Evening planning makes mornings smoother',
            icon: 'schedule',
            actionIcon: 'trending_up',
            actionText: 'Plan Ahead',
            points: 5,
            action: () => { router.push('/dashboard') }
        })
    }

    return suggestions
}

// Actions
const handleCompleteChore = async (chore: any, assignment: any) => {
    try {
        isActioning.value = true
        await choreStore.toggleCompletion(chore, assignment)
        notificationStore.addNotification({
            type: 'success',
            message: `Great job finishing "${chore.name}"`
        })
        refreshSuggestions()
    } catch (error) {
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to complete task'
        })
    } finally {
        isActioning.value = false
    }
}

const handleTakeAction = async () => {
    if (!currentSuggestion.value) return

    try {
        await currentSuggestion.value.action()
        suggestionHistory.value.add(currentSuggestion.value.id)
    } catch (error) {
        console.error('Action failed:', error)
    }
}

const handleDismiss = () => {
    if (!currentSuggestion.value) return

    suggestionHistory.value.add(currentSuggestion.value.id)
    refreshSuggestions()
}

const refreshSuggestions = () => {
    const allSuggestions = generateSuggestions()
    const availableSuggestions = allSuggestions.filter(s =>
        !suggestionHistory.value.has(s.id)
    )

    // Prioritize by urgency then points
    availableSuggestions.sort((a, b) => {
        const priorityWeight = { high: 3, medium: 2, low: 1 }
        const aPriority = priorityWeight[a.priority]
        const bPriority = priorityWeight[b.priority]

        if (aPriority !== bPriority) return bPriority - aPriority
        return b.points - a.points
    })

    currentSuggestion.value = availableSuggestions[0] || null
}

const setupRefreshInterval = () => {
    // Refresh suggestions every 5 minutes
    refreshInterval.value = window.setInterval(refreshSuggestions, 5 * 60 * 1000)
}

// Lifecycle
onMounted(async () => {
    isLoading.value = true

    // Load initial data
    await choreStore.fetchPersonal()

    refreshSuggestions()
    setupRefreshInterval()

    isLoading.value = false
})

onUnmounted(() => {
    if (refreshInterval.value) {
        clearInterval(refreshInterval.value)
    }
})

// Watch for store updates to refresh suggestions
watch([
    () => choreStore.allChores,
    () => listsStore.currentList
], refreshSuggestions)
</script>

<style scoped>
.quick-win-suggestion {
    @apply transition-all duration-micro ease-micro;
    @apply hover:shadow-medium hover:scale-[1.01];
    @apply transform-gpu;
}

/* Loading State */
.suggestion-loading {
    @apply flex items-center gap-3;
    @apply text-text-secondary;
}

.loading-text {
    @apply text-sm font-medium;
}

/* Suggestion Content */
.suggestion-content {
    @apply space-y-4;
}

.suggestion-header {
    @apply flex items-start justify-between;
}

.suggestion-icon {
    @apply flex-shrink-0 w-10 h-10;
    @apply flex items-center justify-center;
    @apply rounded-lg bg-surface-elevated;
    @apply transition-all duration-micro ease-micro;
}

.suggestion-icon svg {
    @apply w-5 h-5;
}

.suggestion-meta {
    @apply flex flex-col gap-1 text-right;
}

.suggestion-type {
    @apply text-xs font-medium text-text-secondary;
    @apply uppercase tracking-wide;
}

.suggestion-points {
    @apply text-sm font-semibold text-primary-600 dark:text-primary-400;
}

/* Suggestion Body */
.suggestion-body {
    @apply space-y-2;
}

.suggestion-title {
    @apply text-lg font-semibold text-text-primary;
    @apply leading-tight;
}

.suggestion-description {
    @apply text-sm text-text-secondary;
    @apply leading-relaxed;
}

.suggestion-context {
    @apply mt-3;
}

.context-indicator {
    @apply inline-flex items-center gap-2;
    @apply px-3 py-1.5;
    @apply bg-warning-50 dark:bg-warning-950/50;
    @apply border border-warning-200 dark:border-warning-800;
    @apply rounded-md;
    @apply text-xs font-medium text-warning-700 dark:text-warning-300;
}

.context-icon {
    @apply w-3.5 h-3.5 flex-shrink-0;
}

/* Suggestion Actions */
.suggestion-actions {
    @apply flex gap-2;
}

.primary-action {
    @apply flex-1;
}

.dismiss-btn {
    @apply flex-shrink-0;
}

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

.empty-icon {
    @apply flex justify-center mb-3;
}

.trophy-icon {
    @apply w-8 h-8 text-success-500;
}

.empty-title {
    @apply text-lg font-semibold text-text-primary mb-2;
}

.empty-description {
    @apply text-sm text-text-secondary;
    @apply max-w-xs mx-auto;
}

/* Responsive adjustments */
@media (max-width: 640px) {
    .suggestion-header {
        @apply flex-col gap-3;
    }

    .suggestion-meta {
        @apply flex-row justify-between text-left;
    }

    .suggestion-actions {
        @apply flex-col;
    }
}
</style>