<template>
    <div class="activity-item" :class="activityClasses" @click="handleClick" @mouseenter="isHovered = true"
        @mouseleave="isHovered = false">
        <!-- Activity Icon with Status -->
        <div class="activity-icon-container">
            <div class="activity-icon" :class="iconClasses">
                <span class="material-icons icon">{{ materialIcon }}</span>

                <!-- Celebration Animation for Completions -->
                <div v-if="isCompletion && showCelebration" class="celebration-particles">
                    <div class="particle" v-for="i in 6" :key="`particle-${i}`"></div>
                </div>
            </div>

            <!-- User Avatar -->
            <div class="user-avatar" v-if="activity.user">
                <div class="avatar-fallback">
                    {{ userInitials }}
                </div>
            </div>
        </div>

        <!-- Activity Content -->
        <div class="activity-content">
            <!-- Message -->
            <div class="activity-message">
                <p class="message-text" v-html="enhancedMessage"></p>

                <!-- Action Badges -->
                <div v-if="actionBadges.length > 0" class="action-badges">
                    <span v-for="badge in actionBadges" :key="badge.text" class="action-badge" :class="badge.variant">
                        {{ badge.text }}
                    </span>
                </div>
            </div>

            <!-- Metadata -->
            <div class="activity-metadata">
                <div class="metadata-left">
                    <time class="activity-time" :datetime="activity.timestamp">
                        {{ formattedTimestamp }}
                    </time>

                    <!-- Location/Context -->
                    <span v-if="contextInfo" class="context-info">
                        <span class="material-icons context-icon">{{ contextInfo.icon }}</span>
                        {{ contextInfo.text }}
                    </span>
                </div>

                <!-- Quick Actions -->
                <div v-if="isHovered && quickActions.length > 0" class="quick-actions">
                    <button v-for="action in quickActions" :key="action.key" class="quick-action-btn"
                        :class="action.variant" @click.stop="handleQuickAction(action)" :aria-label="action.label">
                        <span class="material-icons">{{ action.icon }}</span>
                    </button>
                </div>
            </div>

            <!-- Details Preview -->
            <div v-if="showDetails && activityDetails" class="activity-details">
                <div class="details-content">
                    <div v-for="(value, key) in activityDetails" :key="String(key)" class="detail-item">
                        <span class="detail-label">{{ formatDetailKey(String(key)) }}:</span>
                        <span class="detail-value">{{ formatDetailValue(value) }}</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status Indicator -->
        <div v-if="statusIndicator" class="status-indicator" :class="statusIndicator.variant">
            <span class="material-icons status-icon">{{ statusIndicator.icon }}</span>
        </div>

        <!-- New Activity Pulse -->
        <div v-if="isNew" class="new-activity-pulse"></div>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { formatDistanceToNow } from 'date-fns'
import { type Activity, ActivityEventType } from '@/types/activity'

// Props
interface Props {
    activity: Activity
    isNew?: boolean
    showDetails?: boolean
    compact?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    isNew: false,
    showDetails: false,
    compact: false,
})

// Emits
const emit = defineEmits<{
    'click': [activity: Activity]
    'quick-action': [action: string, activity: Activity]
}>()

// State
const isHovered = ref(false)
const showCelebration = ref(false)

// Computed Properties
const formattedTimestamp = computed(() => {
    return formatDistanceToNow(new Date(props.activity.timestamp), { addSuffix: true })
})

const userInitials = computed(() => {
    if (!props.activity.user?.name) return '?'
    return props.activity.user.name
        .split(' ')
        .map(name => name.charAt(0))
        .join('')
        .substring(0, 2)
        .toUpperCase()
})

const isCompletion = computed(() => {
    return props.activity.event_type.includes('completed')
})

// Icon mapping with Material Icons
const materialIconMap: Record<ActivityEventType, string> = {
    [ActivityEventType.CHORE_COMPLETED]: 'task_alt',
    [ActivityEventType.CHORE_CREATED]: 'add_task',
    [ActivityEventType.EXPENSE_CREATED]: 'payments',
    [ActivityEventType.EXPENSE_SETTLED]: 'receipt_long',
    [ActivityEventType.ITEM_ADDED]: 'add_shopping_cart',
    [ActivityEventType.ITEM_COMPLETED]: 'shopping_cart_checkout',
    [ActivityEventType.USER_JOINED_GROUP]: 'person_add',
}

const materialIcon = computed(() => {
    return materialIconMap[props.activity.event_type] || 'info'
})

// Enhanced message with formatting
const enhancedMessage = computed(() => {
    let message = props.activity.message

    // Bold user names
    const userName = props.activity.user?.name
    if (userName) {
        message = message.replace(userName, `<strong>${userName}</strong>`)
    }

    // Highlight items in quotes
    message = message.replace(/'([^']+)'/g, '<span class="highlighted-item">$1</span>')

    return message
})

// Activity styling classes
const activityClasses = computed(() => [
    'activity-item-base',
    {
        'activity-compact': props.compact,
        'activity-new': props.isNew,
        'activity-completion': isCompletion.value,
        'activity-interactive': true,
    }
])

const iconClasses = computed(() => {
    const baseClasses = ['activity-icon-base']

    switch (props.activity.event_type) {
        case ActivityEventType.CHORE_COMPLETED:
            baseClasses.push('icon-success')
            break
        case ActivityEventType.EXPENSE_CREATED:
            baseClasses.push('icon-warning')
            break
        case ActivityEventType.EXPENSE_SETTLED:
            baseClasses.push('icon-success')
            break
        case ActivityEventType.ITEM_COMPLETED:
            baseClasses.push('icon-success')
            break
        case ActivityEventType.USER_JOINED_GROUP:
            baseClasses.push('icon-primary')
            break
        default:
            baseClasses.push('icon-neutral')
    }

    return baseClasses
})

// Action badges for different activity types
const actionBadges = computed(() => {
    const badges: Array<{ text: string; variant: string }> = []

    if (props.activity.event_type === ActivityEventType.CHORE_COMPLETED) {
        badges.push({ text: 'Completed', variant: 'badge-success' })
    } else if (props.activity.event_type === ActivityEventType.EXPENSE_SETTLED) {
        badges.push({ text: 'Settled', variant: 'badge-success' })
    } else if (props.activity.event_type === ActivityEventType.EXPENSE_CREATED) {
        badges.push({ text: 'New Expense', variant: 'badge-warning' })
    }

    return badges
})

// Context information based on activity type
const contextInfo = computed(() => {
    const details = props.activity.details

    if (details?.list_id) {
        return { icon: 'list', text: 'Shopping List' }
    } else if (details?.chore_name) {
        return { icon: 'home', text: 'Household' }
    } else if (props.activity.event_type.includes('expense')) {
        return { icon: 'account_balance_wallet', text: 'Expenses' }
    }

    return null
})

// Quick actions based on activity type
const quickActions = computed(() => {
    const actions: Array<{ key: string; icon: string; label: string; variant: string }> = []

    if (props.activity.event_type.includes('chore')) {
        actions.push({
            key: 'view-chores',
            icon: 'task_alt',
            label: 'View chores',
            variant: 'action-primary'
        })
    } else if (props.activity.event_type.includes('expense')) {
        actions.push({
            key: 'view-expenses',
            icon: 'payments',
            label: 'View expenses',
            variant: 'action-warning'
        })
    } else if (props.activity.event_type.includes('item')) {
        actions.push({
            key: 'view-lists',
            icon: 'list',
            label: 'View lists',
            variant: 'action-neutral'
        })
    }

    // Always add a "details" action
    actions.push({
        key: 'view-details',
        icon: 'info',
        label: 'View details',
        variant: 'action-neutral'
    })

    return actions
})

// Status indicator for certain activities
const statusIndicator = computed(() => {
    if (props.isNew) {
        return { icon: 'fiber_new', variant: 'status-new' }
    }

    if (isCompletion.value) {
        return { icon: 'check_circle', variant: 'status-success' }
    }

    return null
})

// Activity details for preview
const activityDetails = computed(() => {
    if (!props.showDetails) return null

    const filteredDetails = { ...props.activity.details }
    delete filteredDetails.user_id // Remove internal IDs
    delete filteredDetails.id

    return Object.keys(filteredDetails).length > 0 ? filteredDetails : null
})

// Helper functions
const formatDetailKey = (key: string): string => {
    return key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

const formatDetailValue = (value: any): string => {
    if (typeof value === 'object') {
        return JSON.stringify(value)
    }
    return String(value)
}

// Event handlers
const handleClick = () => {
    emit('click', props.activity)
}

const handleQuickAction = (action: { key: string }) => {
    emit('quick-action', action.key, props.activity)
}

// Lifecycle
onMounted(() => {
    if (isCompletion.value && props.isNew) {
        // Show celebration animation for new completions
        setTimeout(() => {
            showCelebration.value = true
            setTimeout(() => {
                showCelebration.value = false
            }, 2000)
        }, 500)
    }
})
</script>

<style scoped>
.activity-item {
    @apply relative flex items-start gap-3 p-4 transition-all duration-micro cursor-pointer;
}

.activity-item-base {
    @apply hover:bg-neutral-50 rounded-lg;
}

.activity-item.activity-compact {
    @apply p-3;
}

.activity-item.activity-new {
    @apply bg-primary-50/50 border-l-2 border-primary-400;
    animation: slide-in-left 300ms ease-out;
}

.activity-item.activity-completion {
    @apply hover:bg-success-50/50;
}

.activity-item:hover {
    @apply shadow-soft;
}

/* Icon Container */
.activity-icon-container {
    @apply relative flex-shrink-0;
}

.activity-icon {
    @apply w-10 h-10 rounded-full flex items-center justify-center relative overflow-hidden;
    transition: all 150ms ease-micro;
}

.activity-icon-base {
    @apply border-2;
}

.icon-success {
    @apply bg-success-100 border-success-300 text-success-700;
}

.icon-warning {
    @apply bg-warning-100 border-warning-300 text-warning-700;
}

.icon-primary {
    @apply bg-primary-100 border-primary-300 text-primary-700;
}

.icon-neutral {
    @apply bg-neutral-100 border-neutral-300 text-neutral-600;
}

.icon {
    @apply text-lg relative z-10;
}

/* User Avatar */
.user-avatar {
    @apply absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-2 border-white overflow-hidden;
}

.avatar-image {
    @apply w-full h-full object-cover;
}

.avatar-fallback {
    @apply w-full h-full bg-neutral-300 text-white text-xs font-semibold flex items-center justify-center;
}

/* Activity Content */
.activity-content {
    @apply flex-1 min-w-0;
}

.activity-message {
    @apply mb-2;
}

.message-text {
    @apply text-sm text-neutral-800 leading-relaxed;
}

.message-text :deep(strong) {
    @apply font-semibold text-neutral-900;
}

.message-text :deep(.highlighted-item) {
    @apply font-medium text-primary-700 bg-primary-50 px-1 rounded;
}

/* Action Badges */
.action-badges {
    @apply flex flex-wrap gap-2 mt-2;
}

.action-badge {
    @apply inline-flex items-center px-2 py-1 text-xs font-medium rounded-full;
}

.badge-success {
    @apply bg-success-100 text-success-800;
}

.badge-warning {
    @apply bg-warning-100 text-warning-800;
}

.badge-primary {
    @apply bg-primary-100 text-primary-800;
}

/* Metadata */
.activity-metadata {
    @apply flex items-center justify-between;
}

.metadata-left {
    @apply flex items-center gap-3;
}

.activity-time {
    @apply text-xs text-neutral-500 font-medium;
}

.context-info {
    @apply flex items-center gap-1 text-xs text-neutral-500;
}

.context-icon {
    @apply text-sm;
}

/* Quick Actions */
.quick-actions {
    @apply flex items-center gap-1;
    animation: fade-in 150ms ease-out;
}

.quick-action-btn {
    @apply p-1.5 rounded-lg transition-all duration-micro;
}

.action-primary {
    @apply text-primary-600 hover:bg-primary-100;
}

.action-warning {
    @apply text-warning-600 hover:bg-warning-100;
}

.action-neutral {
    @apply text-neutral-500 hover:bg-neutral-100;
}

.quick-action-btn .material-icons {
    @apply text-sm;
}

/* Activity Details */
.activity-details {
    @apply mt-3 p-3 bg-neutral-50 rounded-lg border border-neutral-200;
}

.details-content {
    @apply space-y-1;
}

.detail-item {
    @apply flex gap-2 text-xs;
}

.detail-label {
    @apply font-medium text-neutral-600;
}

.detail-value {
    @apply text-neutral-800;
}

/* Status Indicator */
.status-indicator {
    @apply absolute top-2 right-2 w-6 h-6 rounded-full flex items-center justify-center;
}

.status-new {
    @apply bg-primary-500 text-white;
}

.status-success {
    @apply bg-success-500 text-white;
}

.status-icon {
    @apply text-sm;
}

/* New Activity Pulse */
.new-activity-pulse {
    @apply absolute -top-1 -left-1 w-3 h-3 bg-primary-500 rounded-full;
    animation: pulse-scale 2s infinite;
}

/* Celebration Animation */
.celebration-particles {
    @apply absolute inset-0 pointer-events-none;
}

.particle {
    @apply absolute w-1 h-1 bg-success-400 rounded-full;
    animation: celebration-burst 1.5s ease-out forwards;
}

.particle:nth-child(1) {
    animation-delay: 0ms;
    transform: rotate(0deg);
}

.particle:nth-child(2) {
    animation-delay: 100ms;
    transform: rotate(60deg);
}

.particle:nth-child(3) {
    animation-delay: 200ms;
    transform: rotate(120deg);
}

.particle:nth-child(4) {
    animation-delay: 300ms;
    transform: rotate(180deg);
}

.particle:nth-child(5) {
    animation-delay: 400ms;
    transform: rotate(240deg);
}

.particle:nth-child(6) {
    animation-delay: 500ms;
    transform: rotate(300deg);
}

/* Animations */
@keyframes slide-in-left {
    0% {
        opacity: 0;
        transform: translateX(-20px);
    }

    100% {
        opacity: 1;
        transform: translateX(0);
    }
}

@keyframes fade-in {
    0% {
        opacity: 0;
        transform: scale(0.95);
    }

    100% {
        opacity: 1;
        transform: scale(1);
    }
}

@keyframes pulse-scale {

    0%,
    100% {
        transform: scale(1);
        opacity: 1;
    }

    50% {
        transform: scale(1.5);
        opacity: 0.5;
    }
}

@keyframes celebration-burst {
    0% {
        transform: translateX(0) translateY(0) scale(0);
        opacity: 1;
    }

    100% {
        transform: translateX(20px) translateY(-20px) scale(1);
        opacity: 0;
    }
}

/* Hover effects */
.activity-item:hover .activity-icon {
    transform: scale(1.05);
}

.activity-item.activity-completion:hover .activity-icon.icon-success {
    @apply shadow-success-300;
    box-shadow: 0 0 0 4px rgb(16 185 129 / 20%);
}
</style>