<template>
    <Card class="personal-status-card">
        <!-- Header -->
        <div class="flex items-center justify-between mb-4">
            <Heading size="lg" class="text-neutral-900">
                {{ greeting }}
            </Heading>
            <div class="flex items-center gap-2">
                <div v-if="personalStatus.streakCount > 0" class="streak-indicator">
                    <span class="material-icons text-warning-500 text-sm">local_fire_department</span>
                    <span class="text-xs font-medium text-warning-600">{{ personalStatus.streakCount }}</span>
                </div>
            </div>
        </div>

        <!-- Main Status Content -->
        <div class="status-content">
            <!-- Priority Action -->
            <div v-if="priorityAction" class="priority-action-section mb-6">
                <div class="flex items-start gap-3">
                    <div class="priority-icon">
                        <span class="material-icons" :class="getPriorityIconClass(priorityAction.priority)">
                            {{ getPriorityIcon(priorityAction.type) }}
                        </span>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-sm font-medium text-neutral-900 mb-1">
                            {{ getPriorityActionTitle(priorityAction) }}
                        </h3>
                        <p class="text-xs text-neutral-600 mb-3">
                            {{ getPriorityActionDescription(priorityAction) }}
                        </p>
                        <Button :variant="getPriorityActionVariant(priorityAction.priority)"
                            :color="getPriorityActionColor(priorityAction.priority)" size="sm"
                            @click="handlePriorityAction(priorityAction)" class="w-full">
                            {{ getPriorityActionButtonText(priorityAction) }}
                        </Button>
                    </div>
                </div>
            </div>

            <!-- Empty State -->
            <div v-else class="empty-state text-center py-8">
                <div class="mb-4">
                    <span class="material-icons text-success-400 text-4xl">check_circle</span>
                </div>
                <h3 class="text-sm font-medium text-neutral-900 mb-2">
                    {{ getEmptyStateTitle() }}
                </h3>
                <p class="text-xs text-neutral-600 mb-4">
                    {{ getEmptyStateMessage() }}
                </p>
                <Button variant="soft" color="success" size="sm" @click="handleCreateSomething">
                    {{ getEmptyStateAction() }}
                </Button>
            </div>

            <!-- Quick Stats -->
            <div v-if="priorityAction" class="quick-stats grid grid-cols-3 gap-4 mt-6 pt-6 border-t border-neutral-200">
                <div class="stat-item text-center">
                    <div class="text-lg font-semibold text-neutral-900">{{ personalStatus.completedToday }}</div>
                    <div class="text-xs text-neutral-500">Completed</div>
                </div>
                <div class="stat-item text-center">
                    <div class="text-lg font-semibold" :class="getBalanceColor(personalStatus.netBalance)">
                        {{ formatCurrency(personalStatus.netBalance) }}
                    </div>
                    <div class="text-xs text-neutral-500">Balance</div>
                </div>
                <div class="stat-item text-center">
                    <div class="text-lg font-semibold text-neutral-900">{{ personalStatus.pointsThisWeek }}</div>
                    <div class="text-xs text-neutral-500">Points</div>
                </div>
            </div>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { usePersonalStatus } from '@/composables/usePersonalStatus'
import Card from '@/components/ui/Card.vue'
import Button from '@/components/ui/Button.vue'
import Heading from '@/components/ui/Heading.vue'

interface PriorityAction {
    id: string
    type: 'chore' | 'expense' | 'debt' | 'overdue'
    priority: 'urgent' | 'high' | 'medium' | 'low'
    title: string
    description?: string
    dueDate?: Date
    amount?: number
    actionUrl: string
}

const { personalStatus, priorityAction } = usePersonalStatus()

const greeting = computed(() => {
    const hour = new Date().getHours()
    if (hour < 12) return 'Good morning!'
    if (hour < 17) return 'Good afternoon!'
    return 'Good evening!'
})

const getPriorityIcon = (type: string) => {
    const icons = {
        chore: 'task_alt',
        expense: 'receipt',
        debt: 'payments',
        overdue: 'schedule'
    }
    return icons[type as keyof typeof icons] || 'info'
}

const getPriorityIconClass = (priority: string) => {
    const classes = {
        urgent: 'text-error-500 bg-error-100 p-2 rounded-full',
        high: 'text-warning-500 bg-warning-100 p-2 rounded-full',
        medium: 'text-primary-500 bg-primary-100 p-2 rounded-full',
        low: 'text-neutral-500 bg-neutral-100 p-2 rounded-full'
    }
    return classes[priority as keyof typeof classes] || classes.low
}

const getPriorityActionTitle = (action: PriorityAction) => {
    switch (action.type) {
        case 'chore':
            return `Complete: ${action.title}`
        case 'expense':
            return `Add expense: ${action.title}`
        case 'debt':
            return `Settle up: ${action.title}`
        case 'overdue':
            return `Overdue: ${action.title}`
        default:
            return action.title
    }
}

const getPriorityActionDescription = (action: PriorityAction) => {
    if (action.description) return action.description

    switch (action.type) {
        case 'chore':
            return action.dueDate ? `Due ${formatRelativeTime(action.dueDate)}` : 'Ready to complete'
        case 'expense':
            return 'Quick expense entry'
        case 'debt':
            return action.amount ? `Amount: ${formatCurrency(action.amount)}` : 'Resolve outstanding balance'
        case 'overdue':
            return `This was due ${formatRelativeTime(action.dueDate!)}`
        default:
            return ''
    }
}

const getPriorityActionVariant = (priority: string) => {
    return priority === 'urgent' ? 'solid' : 'soft'
}

const getPriorityActionColor = (priority: string): 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'neutral' => {
    const colors: Record<string, 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'neutral'> = {
        urgent: 'error',
        high: 'warning',
        medium: 'primary',
        low: 'neutral'
    }
    return colors[priority] || 'primary'
}

const getPriorityActionButtonText = (action: PriorityAction) => {
    switch (action.type) {
        case 'chore':
            return 'Mark Complete'
        case 'expense':
            return 'Add Expense'
        case 'debt':
            return 'Settle Up'
        case 'overdue':
            return 'View Details'
        default:
            return 'Take Action'
    }
}

const getEmptyStateTitle = () => {
    const hour = new Date().getHours()
    if (hour < 12) return 'You\'re all caught up!'
    if (hour < 17) return 'Looking good!'
    return 'All done for today!'
}

const getEmptyStateMessage = () => {
    const messages = [
        'No urgent tasks right now. Great job staying on top of things!',
        'Everything is up to date. Maybe add something to your list?',
        'Your household is running smoothly. Time to relax!',
        'All tasks complete! Consider planning something fun.'
    ]
    return messages[Math.floor(Math.random() * messages.length)]
}

const getEmptyStateAction = () => {
    const actions = [
        'Add New Task',
        'Create Shopping List',
        'Plan Chore',
        'Quick Add'
    ]
    return actions[Math.floor(Math.random() * actions.length)]
}

const getBalanceColor = (balance: number) => {
    if (balance > 0) return 'text-success-600'
    if (balance < 0) return 'text-error-600'
    return 'text-neutral-600'
}

const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount)
}

const formatRelativeTime = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) return 'today'
    if (days === 1) return 'yesterday'
    if (days > 0) return `${days} days ago`
    if (days === -1) return 'tomorrow'
    return `in ${Math.abs(days)} days`
}

const handlePriorityAction = (action: PriorityAction) => {
    // This will be handled by the parent component or router
    // For now, we emit an event
    emit('priority-action', action)
}

const handleCreateSomething = () => {
    emit('create-action')
}

const emit = defineEmits<{
    'priority-action': [action: PriorityAction]
    'create-action': []
}>()
</script>

<style scoped>
.personal-status-card {
    @apply bg-white border border-neutral-200 shadow-soft;
    animation: fade-in 300ms ease-out;
}

.priority-action-section {
    @apply p-4 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-100;
}

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

.empty-state {
    @apply px-4;
}

.stat-item {
    transition: transform 150ms ease-micro;
}

.stat-item:hover {
    transform: scale(1.05);
}

.streak-indicator {
    @apply flex items-center gap-1 px-2 py-1 bg-warning-50 rounded-full border border-warning-200;
}
</style>