<template>
    <div class="smart-shopping-item" :class="itemStateClasses">
        <div class="item-content">
            <!-- Drag Handle -->
            <div v-if="isOnline && !isCompleted" class="drag-handle">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <circle cx="9" cy="12" r="1"></circle>
                    <circle cx="9" cy="5" r="1"></circle>
                    <circle cx="9" cy="19" r="1"></circle>
                    <circle cx="15" cy="12" r="1"></circle>
                    <circle cx="15" cy="5" r="1"></circle>
                    <circle cx="15" cy="19" r="1"></circle>
                </svg>
            </div>

            <!-- Checkbox and Item Info -->
            <div class="item-main">
                <div class="checkbox-section">
                    <input type="checkbox" :checked="item.is_complete" @change="handleToggleComplete"
                        :disabled="!canToggle" class="item-checkbox" />
                    <div class="item-info">
                        <h4 class="item-name">{{ item.name }}</h4>
                        <p v-if="item.quantity" class="item-quantity">Qty: {{ item.quantity }}</p>

                        <!-- Claim Status -->
                        <div v-if="claimStatusText" class="claim-status">
                            <span class="claim-text">{{ claimStatusText }}</span>
                            <span v-if="claimTimeText" class="claim-time">{{ claimTimeText }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="item-actions">
                <!-- Claim/Unclaim Buttons -->
                <Button v-if="canClaim" variant="outline" size="sm" @click="$emit('claim', item)" :disabled="!isOnline"
                    class="claim-btn">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                    </svg>
                    Claim
                </Button>

                <Button v-if="canUnclaim" variant="outline" size="sm" @click="$emit('unclaim', item)"
                    :disabled="!isOnline" class="unclaim-btn">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M6 18L18 6M6 6l12 12" />
                    </svg>
                    Unclaim
                </Button>

                <!-- Price Input -->
                <div v-if="isCompleted" class="price-section">
                    <input type="number" :value="item.price || ''" @input="handlePriceUpdate" placeholder="$0.00"
                        step="0.01" min="0" class="price-input" />
                </div>

                <!-- Edit Button -->
                <Button variant="ghost" size="sm" @click="$emit('edit', item)" class="edit-btn" aria-label="Edit item">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                </Button>
            </div>
        </div>

        <!-- Progress Indicator for Claimed Items -->
        <div v-if="isClaimedByMe && !isCompleted" class="claimed-indicator">
            <div class="claimed-bar"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { PropType } from 'vue'
import { formatDistanceToNow } from 'date-fns'
import { useAuthStore } from '@/stores/auth'
import type { Item } from '@/types/item'
import type { List } from '@/types/list'
import { Button } from '@/components/ui'

const props = defineProps({
    item: {
        type: Object as PropType<Item>,
        required: true
    },
    list: {
        type: Object as PropType<List>,
        required: true
    },
    isOnline: {
        type: Boolean,
        default: true
    },
    isClaimedByMe: {
        type: Boolean,
        default: false
    },
    isClaimedByOthers: {
        type: Boolean,
        default: false
    },
    isCompleted: {
        type: Boolean,
        default: false
    },
    readonly: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits([
    'claim',
    'unclaim',
    'complete',
    'update-price',
    'edit'
])

const authStore = useAuthStore()
const currentUser = computed(() => authStore.user)

// Computed properties
const itemStateClasses = computed(() => ({
    'is-completed': props.item.is_complete,
    'is-claimed-by-me': props.isClaimedByMe,
    'is-claimed-by-others': props.isClaimedByOthers,
    'is-readonly': props.readonly
}))

const canClaim = computed(() => {
    return (
        props.list.group_id &&
        !props.item.is_complete &&
        !props.item.claimed_by_user_id &&
        !props.readonly &&
        props.isOnline
    )
})

const canUnclaim = computed(() => {
    return (
        props.item.claimed_by_user_id === currentUser.value?.id &&
        !props.readonly &&
        props.isOnline
    )
})

const canToggle = computed(() => {
    return (
        props.isOnline &&
        !props.readonly &&
        (props.isClaimedByMe || !props.list.group_id || !props.item.claimed_by_user_id)
    )
})

const claimStatusText = computed(() => {
    if (!props.item.claimed_by_user_id) return ''

    const claimer = props.item.claimed_by_user_id === currentUser.value?.id
        ? 'You'
        : props.item.claimed_by_user?.name || 'Someone'

    return `${claimer} claimed this`
})

const claimTimeText = computed(() => {
    if (!props.item.claimed_at) return ''

    try {
        return formatDistanceToNow(new Date(props.item.claimed_at), { addSuffix: true })
    } catch (error) {
        return ''
    }
})

// Event handlers
const handleToggleComplete = (event: Event) => {
    const target = event.target as HTMLInputElement
    emit('complete', props.item, target.checked)
}

const handlePriceUpdate = (event: Event) => {
    const target = event.target as HTMLInputElement
    const price = parseFloat(target.value) || 0
    emit('update-price', props.item, price)
}
</script>

<style scoped>
.smart-shopping-item {
    @apply relative bg-white transition-all duration-200 ease-out;
}

.smart-shopping-item:hover {
    @apply bg-neutral-50;
}

.smart-shopping-item.is-completed {
    @apply opacity-60;
}

.smart-shopping-item.is-claimed-by-me {
    @apply bg-blue-50 border-l-4 border-l-blue-500;
}

.smart-shopping-item.is-claimed-by-others {
    @apply bg-amber-50 border-l-4 border-l-amber-500;
}

.smart-shopping-item.is-readonly {
    @apply cursor-default;
}

.item-content {
    @apply flex items-center p-4 gap-3;
}

.drag-handle {
    @apply text-neutral-400 cursor-move;
}

.item-main {
    @apply flex-1;
}

.checkbox-section {
    @apply flex items-start gap-3;
}

.item-checkbox {
    @apply w-5 h-5 rounded border-2 border-neutral-300 text-blue-600 focus:ring-blue-500 focus:ring-2 focus:ring-offset-2;
    @apply transition-colors duration-200;
}

.item-checkbox:checked {
    @apply bg-blue-600 border-blue-600;
}

.item-info {
    @apply flex-1;
}

.item-name {
    @apply font-medium text-neutral-900 mb-1;
}

.is-completed .item-name {
    @apply line-through text-neutral-500;
}

.item-quantity {
    @apply text-sm text-neutral-600 mb-1;
}

.claim-status {
    @apply flex items-center gap-2 text-xs;
}

.claim-text {
    @apply font-medium text-neutral-700;
}

.is-claimed-by-me .claim-text {
    @apply text-blue-700;
}

.is-claimed-by-others .claim-text {
    @apply text-amber-700;
}

.claim-time {
    @apply text-neutral-500;
}

.item-actions {
    @apply flex items-center gap-2;
}

.claim-btn,
.unclaim-btn {
    @apply whitespace-nowrap;
}

.claim-btn {
    @apply border-blue-300 text-blue-700 hover:bg-blue-50;
}

.unclaim-btn {
    @apply border-amber-300 text-amber-700 hover:bg-amber-50;
}

.price-section {
    @apply flex items-center;
}

.price-input {
    @apply w-20 px-2 py-1 text-sm border border-neutral-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
    @apply transition-colors duration-200;
}

.edit-btn {
    @apply text-neutral-500 hover:text-neutral-700;
}

.claimed-indicator {
    @apply absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-blue-500 to-blue-600;
    @apply overflow-hidden;
}

.claimed-bar {
    @apply h-full w-full bg-blue-500 animate-pulse;
}

/* Animation for claim status changes */
.smart-shopping-item {
    @apply transition-all duration-300 ease-out;
}

@keyframes claim-highlight {
    0% {
        @apply bg-blue-100;
    }

    100% {
        @apply bg-blue-50;
    }
}

.is-claimed-by-me {
    animation: claim-highlight 0.5s ease-out;
}
</style>