<template>
    <Card class="chore-card" :class="getCardClasses()">
        <!-- Chore Header -->
        <div class="chore-header">
            <div class="chore-info">
                <div class="chore-priority">
                    <span class="material-icons" :class="getPriorityIconClasses()">
                        {{ getPriorityIcon() }}
                    </span>
                </div>
                <div class="chore-details">
                    <h3 class="chore-title">{{ chore.name }}</h3>
                    <p v-if="chore.description" class="chore-description">
                        {{ chore.description }}
                    </p>
                    <div class="chore-meta">
                        <span class="chore-due-date" :class="getDueDateClasses()">
                            {{ getDueDateText() }}
                        </span>
                        <div class="chore-points">
                            <span class="material-icons text-warning-500">star</span>
                            <span class="points-text">{{ chore.points }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Assignment Info -->
            <div v-if="chore.assignedTo && !chore.isAvailable" class="assignment-info">
                <div class="assigned-avatar">
                    <span class="avatar-initials">
                        {{ getAssignedUser()?.name?.charAt(0) || getAssignedUser()?.full_name?.charAt(0) || '?' }}
                    </span>
                </div>
            </div>
        </div>

        <!-- Progress Indicator (for recurring chores) -->
        <div v-if="chore.estimatedDuration" class="progress-section">
            <div class="progress-info">
                <span class="material-icons text-neutral-400">schedule</span>
                <span class="duration-text">{{ formatDuration(chore.estimatedDuration) }}</span>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="chore-actions">
            <!-- Complete Action (for assigned chores) -->
            <Button v-if="canCompleteChore()" variant="solid" color="success" size="sm" fullWidth
                @click="handleComplete" :loading="isCompleting">
                <template #icon-left>
                    <span class="material-icons">check_circle</span>
                </template>
                Mark Complete
            </Button>

            <!-- Claim Action (for available chores) -->
            <Button v-else-if="canClaimChore()" variant="outline" color="primary" size="sm" fullWidth
                @click="handleClaim" :loading="isClaiming">
                <template #icon-left>
                    <span class="material-icons">volunteer_activism</span>
                </template>
                Claim This Chore
            </Button>

            <!-- View Details Action (for completed/unassigned) -->
            <Button v-else variant="ghost" color="neutral" size="sm" fullWidth @click="handleViewDetails">
                <template #icon-left>
                    <span class="material-icons">info</span>
                </template>
                {{ category === 'archive' ? 'View Details' : 'Details' }}
            </Button>
        </div>

        <!-- Completion Celebration (for archive) -->
        <div v-if="category === 'archive' && chore.completedBy" class="completion-info">
            <div class="completion-badge">
                <span class="material-icons text-success-500">celebration</span>
                <span class="completion-text">
                    Completed by {{ getCompletedByUser()?.name || getCompletedByUser()?.full_name || 'Someone' }}
                </span>
                <span class="completion-date">
                    {{ formatCompletionDate() }}
                </span>
            </div>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useGroupStore } from '@/stores/groupStore'
import Card from '@/components/ui/Card.vue'
import Button from '@/components/ui/Button.vue'
import type { UserPublic } from '@/types/user'

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 props = defineProps<{
    chore: Chore
    category: 'priority' | 'upcoming' | 'available' | 'archive'
}>()

const emit = defineEmits<{
    complete: [chore: Chore]
    claim: [chore: Chore]
    'view-details': [chore: Chore]
}>()

const authStore = useAuthStore()
const groupStore = useGroupStore()

const isCompleting = ref(false)
const isClaiming = ref(false)

// User lookup functions
const getAssignedUser = (): UserPublic | null => {
    if (!props.chore.assignedTo || !groupStore.currentGroup) return null
    return groupStore.currentGroup.members.find((member: UserPublic) => member.id.toString() === props.chore.assignedTo) || null
}

const getCompletedByUser = (): UserPublic | null => {
    if (!props.chore.completedBy || !groupStore.currentGroup) return null
    return groupStore.currentGroup.members.find((member: UserPublic) => member.id.toString() === props.chore.completedBy) || null
}

// Permission checks
const canCompleteChore = (): boolean => {
    if (props.chore.isComplete) return false
    if (props.chore.isAvailable) return false
    if (!props.chore.assignedTo) return false
    return props.chore.assignedTo === authStore.user?.id
}

const canClaimChore = (): boolean => {
    if (props.chore.isComplete) return false
    return props.chore.isAvailable
}

// Styling functions
const getCardClasses = () => {
    const classes = ['transition-all duration-micro hover:shadow-medium']

    if (props.chore.isOverdue) {
        classes.push('border-error-200 bg-error-50')
    } else if (props.category === 'priority') {
        classes.push('border-warning-200 bg-warning-50')
    } else if (props.category === 'archive') {
        classes.push('border-success-200 bg-success-50')
    }

    return classes.join(' ')
}

const getPriorityIcon = () => {
    const icons = {
        urgent: 'priority_high',
        high: 'trending_up',
        medium: 'remove',
        low: 'trending_down'
    }
    return icons[props.chore.priority] || 'remove'
}

const getPriorityIconClasses = () => {
    const classes = {
        urgent: 'text-error-500',
        high: 'text-warning-500',
        medium: 'text-primary-500',
        low: 'text-neutral-500'
    }
    return classes[props.chore.priority] || 'text-neutral-500'
}

const getDueDateClasses = () => {
    if (props.chore.isOverdue) {
        return 'text-error-600 font-medium'
    } else if (props.category === 'priority') {
        return 'text-warning-600 font-medium'
    }
    return 'text-neutral-600'
}

const getDueDateText = () => {
    const dueDate = new Date(props.chore.dueDate)
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)

    if (props.chore.isOverdue) {
        const daysDiff = Math.floor((now.getTime() - dueDate.getTime()) / (24 * 60 * 60 * 1000))
        if (daysDiff === 0) return 'Due today'
        if (daysDiff === 1) return 'Due yesterday'
        return `Overdue by ${daysDiff} days`
    }

    if (dueDate.toDateString() === today.toDateString()) {
        return 'Due today'
    } else if (dueDate.toDateString() === tomorrow.toDateString()) {
        return 'Due tomorrow'
    } else {
        return `Due ${dueDate.toLocaleDateString()}`
    }
}

const formatDuration = (minutes: number): string => {
    if (minutes < 60) {
        return `${minutes}min`
    }
    const hours = Math.floor(minutes / 60)
    const remainingMinutes = minutes % 60
    if (remainingMinutes === 0) {
        return `${hours}h`
    }
    return `${hours}h ${remainingMinutes}m`
}

const formatCompletionDate = (): string => {
    if (!props.chore.completedAt) return ''

    const completedDate = new Date(props.chore.completedAt)
    const now = new Date()
    const diffInDays = Math.floor((now.getTime() - completedDate.getTime()) / (24 * 60 * 60 * 1000))

    if (diffInDays === 0) return 'today'
    if (diffInDays === 1) return 'yesterday'
    if (diffInDays < 7) return `${diffInDays} days ago`
    return completedDate.toLocaleDateString()
}

// Event handlers
const handleComplete = async () => {
    isCompleting.value = true
    try {
        emit('complete', props.chore)
    } finally {
        isCompleting.value = false
    }
}

const handleClaim = async () => {
    isClaiming.value = true
    try {
        emit('claim', props.chore)
    } finally {
        isClaiming.value = false
    }
}

const handleViewDetails = () => {
    emit('view-details', props.chore)
}
</script>

<style scoped>
.chore-card {
    @apply p-4 space-y-4;
    @apply border border-neutral-200 bg-white rounded-lg;
}

.chore-header {
    @apply flex items-start justify-between gap-4;
}

.chore-info {
    @apply flex-1 min-w-0 flex gap-3;
}

.chore-priority {
    @apply flex-shrink-0 mt-1;
}

.chore-details {
    @apply flex-1 min-w-0;
}

.chore-title {
    @apply text-base font-medium text-neutral-900 mb-1;
    @apply line-clamp-2;
}

.chore-description {
    @apply text-sm text-neutral-600 mb-2;
    @apply line-clamp-2;
}

.chore-meta {
    @apply flex items-center justify-between gap-2;
}

.chore-due-date {
    @apply text-xs;
}

.chore-points {
    @apply flex items-center gap-1;
}

.points-text {
    @apply text-xs font-medium text-warning-600;
}

.assignment-info {
    @apply flex-shrink-0;
}

.assigned-avatar {
    @apply w-8 h-8 rounded-full overflow-hidden bg-primary-100;
    @apply flex items-center justify-center;
}

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

.avatar-initials {
    @apply text-xs font-medium text-primary-600;
}

.progress-section {
    @apply pt-2 border-t border-neutral-100;
}

.progress-info {
    @apply flex items-center gap-2;
}

.duration-text {
    @apply text-xs text-neutral-600;
}

.chore-actions {
    @apply pt-2;
}

.completion-info {
    @apply pt-3 border-t border-success-200;
}

.completion-badge {
    @apply flex items-center gap-2 text-xs;
}

.completion-text {
    @apply text-success-700 font-medium;
}

.completion-date {
    @apply text-success-600;
}

/* Mobile optimizations */
@media (max-width: 640px) {
    .chore-card {
        @apply p-3 space-y-3;
    }

    .chore-title {
        @apply text-sm;
    }

    .chore-description {
        @apply text-xs;
    }

    .assigned-avatar {
        @apply w-6 h-6;
    }

    .avatar-initials {
        @apply text-xs;
    }
}

/* Animation states */
.chore-card:hover {
    @apply scale-[1.02] transform-gpu;
}

.chore-card:active {
    @apply scale-[0.98] transform-gpu;
}

/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
    .chore-card {
        @apply transition-none;
    }

    .chore-card:hover,
    .chore-card:active {
        @apply transform-none;
    }
}
</style>