<template>
    <div class="dashboard-page">
        <!-- Hero Section - Personal Status Above Fold -->
        <section class="hero-section">
            <div class="hero-content">
                <header class="dashboard-header">
                    <h1 class="greeting">{{ timeBasedGreeting }}</h1>
                    <p class="status-subtitle">{{ statusMessage }}</p>
                </header>

                <QuickChoreAdd @chore-added="handleChoreAdded" class="mb-4" />

                <!-- Personal Status Card - Single source of truth -->
                <PersonalStatusCard @priority-action="handlePriorityAction" @create-action="handleCreateAction"
                    class="status-card" />
            </div>
        </section>

        <!-- Quick Actions - Contextual and Smart -->
        <section class="quick-actions-section">
            <div class="section-header">
                <span class="section-badge">{{ t('dashboard.mostUsed', 'Most Used') }}</span>
            </div>

            <div class="quick-actions-grid">
                <!-- Contextual Quick Actions -->
                <button v-for="action in contextualActions" :key="action.id" class="quick-action-button"
                    :class="action.styleClass" @click="action.handler">
                    <div class="action-icon-container">
                        <span class="material-icons">{{ action.icon }}</span>
                        <span v-if="action.badge" class="action-badge">{{ action.badge }}</span>
                    </div>
                    <div class="action-content">
                        <h3 class="action-title">{{ action.title }}</h3>
                        <p class="action-subtitle">{{ action.subtitle }}</p>
                    </div>
                    <span class="material-icons action-arrow">arrow_forward</span>
                </button>
            </div>
        </section>

        <!-- Activity Feed - Social Proof -->
        <section class="activity-section">
            <Suspense>
                <template #default>
                    <ActivityFeed @activity-action="handleActivityAction" />
                </template>
                <template #fallback>
                    <div class="activity-skeleton">
                        <div v-for="i in 3" :key="i" class="activity-skeleton-item">
                            <div class="skeleton-avatar"></div>
                            <div class="skeleton-content">
                                <div class="skeleton-line"></div>
                                <div class="skeleton-line short"></div>
                            </div>
                            <div class="skeleton-time"></div>
                        </div>
                    </div>
                </template>
            </Suspense>
        </section>

        <!-- Insights Section - Data Driven -->
        <section v-if="insights.length > 0" class="insights-section">
            <div class="section-header">
                <h2 class="section-title">{{ t('dashboard.insights', 'Insights') }}</h2>
                <span class="section-badge insights">{{ t('dashboard.personalized', 'Personalized') }}</span>
            </div>

            <div class="insights-grid">
                <div v-for="insight in insights" :key="insight.id" class="insight-card" :class="insight.type">
                    <div class="insight-icon">
                        <span class="material-icons">{{ insight.icon }}</span>
                    </div>
                    <div class="insight-content">
                        <h3 class="insight-title">{{ insight.title }}</h3>
                        <p class="insight-description">{{ insight.description }}</p>
                        <Button v-if="insight.action" variant="ghost" size="sm" @click="insight.action.handler"
                            class="insight-action">
                            {{ insight.action.label }}
                        </Button>
                    </div>
                </div>
            </div>
        </section>

        <!-- Universal FAB Integration -->
        <!-- <UniversalFAB @scan-receipt="handleScanReceipt" @create-list="handleCreateList"
            @invite-member="handleInviteMember" @quick-expense="handleQuickExpense" /> -->

        <!-- Global Notifications -->
        <NotificationDisplay />

        <!-- Quick Action Modals -->
        <Teleport to="body">
            <QuickExpenseModal v-model="showQuickExpenseModal" @expense-created="handleExpenseCreated" />
            <ReceiptScannerModal v-model="showReceiptScanModal" @receipt-processed="handleReceiptProcessed" />
        </Teleport>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useGroupStore } from '@/stores/groupStore'
import { useNotificationStore } from '@/stores/notifications'
import { useChoreStore } from '@/stores/choreStore'
import { useExpensesStore } from '@/stores/expensesStore'
import { useAuthStore } from '@/stores/auth'
import PersonalStatusCard from '@/components/dashboard/PersonalStatusCard.vue'
import ActivityFeed from '@/components/dashboard/ActivityFeed.vue'
// import UniversalFAB from '@/components/dashboard/UniversalFAB.vue'
import QuickChoreAdd from '@/components/QuickChoreAdd.vue'
import NotificationDisplay from '@/components/global/NotificationDisplay.vue'
import Button from '@/components/ui/Button.vue'
// import QuickExpenseModal from '@/components/expenses/QuickExpenseModal.vue'
import ReceiptScannerModal from '@/components/ReceiptScannerModal.vue'
import { preloadManager } from '@/utils/advancedPerformance'
import { storeToRefs } from 'pinia'

const { t } = useI18n()
const router = useRouter()
const groupStore = useGroupStore()
const notificationStore = useNotificationStore()
const choreStore = useChoreStore()
const expensesStore = useExpensesStore()
const authStore = useAuthStore()

// Reactive state
const showQuickExpenseModal = ref(false)
const showReceiptScanModal = ref(false)

const { user } = storeToRefs(authStore)

// Smart greeting based on time and user context
const timeBasedGreeting = computed(() => {
    const hour = new Date().getHours()
    const name = user.value?.name?.split(' ')[0] || 'there'

    if (hour < 12) return t('dashboard.greeting.morning', `Good morning, ${name}!`)
    if (hour < 17) return t('dashboard.greeting.afternoon', `Good afternoon, ${name}!`)
    return t('dashboard.greeting.evening', `Good evening, ${name}!`)
})

// Dynamic status message based on context
const statusMessage = computed(() => {
    const overdueCount = choreStore.overdueChores.length
    const pendingExpenses = Object.keys(expensesStore.pendingSettlements).length

    if (overdueCount > 0) {
        return t('dashboard.status.overdue', `You have ${overdueCount} overdue chore${overdueCount > 1 ? 's' : ''}`)
    }

    if (pendingExpenses > 0) {
        return t('dashboard.status.expenses', `${pendingExpenses} expense${pendingExpenses > 1 ? 's' : ''} to review`)
    }

    return t('dashboard.status.upToDate', "You're all caught up! 🎉")
})

// Smart contextual actions based on user behavior and data
const contextualActions = computed(() => {
    const actions = []

    // Most used: Add Expense (80% usage)
    actions.push({
        id: 'add-expense',
        title: t('dashboard.actions.addExpense', 'Add Expense'),
        subtitle: t('dashboard.actions.addExpenseDesc', 'Split a bill with household'),
        icon: 'receipt_long',
        styleClass: 'primary',
        badge: null,
        handler: () => showQuickExpenseModal.value = true
    })

    // Context-aware: Lists (using name-based filter for 'shopping')
    const shoppingListsCount = groupStore.groups.filter(g => g.name && g.name.toLowerCase().includes('shopping')).length
    if (shoppingListsCount > 0) {
        actions.push({
            id: 'shopping-list',
            title: t('dashboard.actions.shoppingList', 'Shopping List'),
            subtitle: t('dashboard.actions.shoppingListDesc', 'Add items to grocery list'),
            icon: 'shopping_cart',
            styleClass: 'secondary',
            badge: String(shoppingListsCount),
            handler: () => router.push('/lists?type=shopping')
        })
    }

    // Smart: Scan Receipt if expenses exist
    if (expensesStore.expenses.length > 0) {
        actions.push({
            id: 'scan-receipt',
            title: t('dashboard.actions.scanReceipt', 'Scan Receipt'),
            subtitle: t('dashboard.actions.scanReceiptDesc', 'Quick expense from photo'),
            icon: 'photo_camera',
            styleClass: 'tertiary smart',
            badge: null,
            handler: () => showReceiptScanModal.value = true
        })
    }

    return actions.slice(0, 3) // Max 3 for clean layout
})

// Smart insights based on user data and patterns
const insights = computed(() => {
    const insightsList: any[] = []

    // Financial insight (example: compare this month vs last month)
    // You may want to add a getter in expensesStore for monthly/lastMonth spending, but for now, skip this insight if not available

    // Chore completion insight (example: completion rate)
    // You may want to add a getter in choreStore for completion rate, but for now, skip this insight if not available

    // Group efficiency insight (example: most active member)
    // You may want to add a getter in groupStore for member activity, but for now, skip this insight if not available

    return insightsList
})

const hasOverdueChores = computed(() => choreStore.overdueChores.length > 0)

// Event handlers with optimistic updates
const handlePriorityAction = (action: any) => {
    // Preload the target route for instant navigation
    preloadManager.preloadRoute(action.routeKey)

    router.push(action.actionUrl)

    notificationStore.addNotification({
        type: 'info',
        message: t('dashboard.navigating', `Opening ${action.title}...`),
        duration: 1500
    })
}

const handleCreateAction = () => {
    router.push('/lists?create=true')
}

const handleChoreAdded = (chore: any) => {
    notificationStore.addNotification({
        type: 'success',
        message: t('dashboard.choreAdded', `"${chore.name}" added successfully!`),
        duration: 3000
    })

    // Refresh chore data
    // If you want to refresh, call fetchPersonal() and/or fetchGroup() as needed
    // choreStore.fetchPersonal()
}

const handleActivityAction = (activity: any) => {
    // Handle interactions with activity feed items
    if (activity.actionUrl) {
        router.push(activity.actionUrl)
    }
}

// const handleQuickExpense = () => {
//     showQuickExpenseModal.value = true
// }

const handleExpenseCreated = (expense: any) => {
    showQuickExpenseModal.value = false

    notificationStore.addNotification({
        type: 'success',
        message: t('dashboard.expenseCreated', `Expense "${expense.description}" created!`),
        duration: 3000
    })

    // Refresh expense data
    expensesStore.fetchExpenses()
}

const handleReceiptProcessed = (receipt: any) => {
    showReceiptScanModal.value = false

    notificationStore.addNotification({
        type: 'success',
        message: t('dashboard.receiptProcessed', 'Receipt processed successfully!'),
        duration: 3000
    })

    // Navigate to expense creation with pre-filled data
    router.push(`/expenses/new?from=receipt&data=${encodeURIComponent(JSON.stringify(receipt))}`)
}

// const handleCreateList = () => {
//     router.push('/lists?create=true')
// }

// const handleInviteMember = () => {
//     router.push('/groups?invite=true')
// }

const navigateToActivity = () => {
    router.push('/activity')
}

// Performance optimizations
onMounted(async () => {
    try {
        // Parallel data loading for better UX
        const promises = [
            groupStore.fetchUserGroups(),
            // choreStore.fetchPersonal(), // Uncomment if you want to fetch chores
            expensesStore.fetchExpenses()
        ]

        await Promise.allSettled(promises)

        // Preload likely next routes based on dashboard context
        preloadManager.preloadLikelyRoutes('dashboard')
    } catch (error) {
        console.error('Failed to load dashboard data:', error)

        notificationStore.addNotification({
            type: 'error',
            message: t('dashboard.loadError', 'Failed to load some data. Please refresh.'),
            duration: 5000
        })
    }
})

// Reactive updates for live data
watch(() => choreStore.overdueChores.length, (newCount, oldCount) => {
    if (newCount > oldCount && newCount > 0) {
        notificationStore.addNotification({
            type: 'warning',
            message: t('dashboard.overdueAlert', `You have ${newCount} overdue chore${newCount > 1 ? 's' : ''}!`),
            duration: 4000
        })
    }
})
</script>

<style scoped lang="scss">
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');

.dashboard-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    padding: 0;

    @media (min-width: 768px) {
        padding: 0 1rem;
    }
}

/* Hero Section - Above Fold */
.hero-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 2rem 1rem 3rem;
    margin-bottom: 2rem;
    position: relative;
    overflow: hidden;

    &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url("data:image/svg+xml,%3Csvg width='40' height='40' viewBox='0 0 40 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M20 20c0 5.5-4.5 10-10 10s-10-4.5-10-10 4.5-10 10-10 10 4.5 10 10zm10 0c0 5.5-4.5 10-10 10s-10-4.5-10-10 4.5-10 10-10 10 4.5 10 10z'/%3E%3C/g%3E%3C/svg%3E");
    }

    @media (min-width: 768px) {
        border-radius: 16px;
        margin: 1rem 0 2rem;
        padding: 3rem 2rem 4rem;
    }
}

.hero-content {
    max-width: 1200px;
    margin: 0 auto;
    position: relative;
    z-index: 1;
}

.dashboard-header {
    text-align: center;
    margin-bottom: 2rem;

    @media (min-width: 768px) {
        text-align: left;
    }
}

.greeting {
    font-size: 2rem;
    font-weight: 700;
    margin: 0 0 0.5rem 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    @media (min-width: 768px) {
        font-size: 2.5rem;
    }
}

.status-subtitle {
    font-size: 1.1rem;
    opacity: 0.9;
    margin: 0;
    font-weight: 300;
}

.status-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    padding: 1.5rem;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #1f2937;

    @media (min-width: 768px) {
        padding: 2rem;
    }
}

/* Sections */
.quick-actions-section,
.activity-section,
.insights-section {
    max-width: 1200px;
    margin: 0 auto 3rem;
    padding: 0 1rem;
}

.section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 1rem;
}

.section-title {
    font-size: 1.5rem;
    font-weight: 600;
    color: #1f2937;
    margin: 0;

    @media (min-width: 768px) {
        font-size: 1.75rem;
    }
}

.section-badge {
    padding: 0.25rem 0.75rem;
    background: #e0e7ff;
    color: #3730a3;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;

    &.insights {
        background: #ecfdf5;
        color: #047857;
    }
}

/* Quick Actions Grid */
.quick-actions-grid {
    display: grid;
    gap: 1rem;
    grid-template-columns: 1fr;

    @media (min-width: 640px) {
        grid-template-columns: repeat(2, 1fr);
    }

    @media (min-width: 1024px) {
        grid-template-columns: repeat(3, 1fr);
    }
}

.quick-action-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
    border: 1px solid #e5e7eb;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    &.pulse-subtle {
        animation: pulse-subtle 3s ease-in-out infinite;
    }
}

.quick-action-button {
    display: flex;
    align-items: center;
    gap: 1rem;
    width: 100%;
    padding: 1.5rem;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    text-align: left;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        border-color: #d1d5db;
    }

    &.primary {
        border-color: #3b82f6;

        .action-icon-container {
            background: #eff6ff;
            color: #2563eb;
        }
    }

    &.secondary {
        border-color: #10b981;

        .action-icon-container {
            background: #ecfdf5;
            color: #059669;
        }
    }

    &.tertiary {
        border-color: #f59e0b;

        .action-icon-container {
            background: #fffbeb;
            color: #d97706;
        }
    }

    &.smart {
        position: relative;

        &::after {
            content: '✨';
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            font-size: 0.875rem;
        }
    }
}

.action-icon-container {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 12px;
    background: #f3f4f6;
    color: #6b7280;
    flex-shrink: 0;

    .material-icons {
        font-size: 24px;
    }
}

.action-badge {
    position: absolute;
    top: -4px;
    right: -4px;
    background: #ef4444;
    color: white;
    font-size: 0.75rem;
    font-weight: 600;
    padding: 2px 6px;
    border-radius: 8px;
    min-width: 16px;
    text-align: center;
}

.action-content {
    flex-grow: 1;
    min-width: 0;
}

.action-title {
    font-size: 1rem;
    font-weight: 600;
    color: #111827;
    margin: 0 0 0.25rem 0;
}

.action-subtitle {
    font-size: 0.875rem;
    color: #6b7280;
    margin: 0;
    line-height: 1.4;
}

.action-arrow {
    color: #9ca3af;
    font-size: 20px;
    flex-shrink: 0;
    transition: transform 0.2s ease;
}

.quick-action-button:hover .action-arrow {
    transform: translateX(4px);
}

/* Insights Grid */
.insights-grid {
    display: grid;
    gap: 1rem;
    grid-template-columns: 1fr;

    @media (min-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
    }

    @media (min-width: 1024px) {
        grid-template-columns: repeat(3, 1fr);
    }
}

.insight-card {
    display: flex;
    gap: 1rem;
    padding: 1.5rem;
    background: white;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    transition: all 0.2s ease;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    &.financial {
        border-left: 4px solid #3b82f6;
    }

    &.achievement {
        border-left: 4px solid #10b981;
    }

    &.social {
        border-left: 4px solid #8b5cf6;
    }
}

.insight-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: #f3f4f6;
    color: #6b7280;
    flex-shrink: 0;

    .material-icons {
        font-size: 20px;
    }
}

.insight-content {
    flex-grow: 1;
}

.insight-title {
    font-size: 0.875rem;
    font-weight: 600;
    color: #111827;
    margin: 0 0 0.25rem 0;
}

.insight-description {
    font-size: 0.8rem;
    color: #6b7280;
    margin: 0 0 0.75rem 0;
    line-height: 1.4;
}

.insight-action {
    font-size: 0.8rem;
    padding: 0.25rem 0.5rem;
    height: auto;
}

/* Activity Skeleton */
.activity-skeleton {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid #e5e7eb;
}

.activity-skeleton-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem 0;
    border-bottom: 1px solid #f3f4f6;

    &:last-child {
        border-bottom: none;
    }
}

.skeleton-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-shimmer 1.5s infinite;
}

.skeleton-content {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.skeleton-line {
    height: 1rem;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-shimmer 1.5s infinite;
    border-radius: 4px;

    &.short {
        width: 60%;
    }
}

.skeleton-time {
    width: 60px;
    height: 0.875rem;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-shimmer 1.5s infinite;
    border-radius: 4px;
}

/* Animations */
@keyframes pulse-subtle {

    0%,
    100% {
        transform: scale(1);
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    50% {
        transform: scale(1.02);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
    }
}

@keyframes skeleton-shimmer {
    0% {
        background-position: 200% 0;
    }

    100% {
        background-position: -200% 0;
    }
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
    .dashboard-page {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
    }

    .section-title {
        color: #f1f5f9;
    }

    .quick-action-card,
    .quick-action-button,
    .insight-card,
    .activity-skeleton {
        background: #334155;
        border-color: #475569;
        color: #f1f5f9;
    }

    .action-title,
    .insight-title {
        color: #f1f5f9;
    }

    .action-subtitle,
    .insight-description {
        color: #cbd5e1;
    }
}

/* Accessibility */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
}
</style>