<template>
    <div class="list-item-wrapper" :class="{ 'is-complete': item.is_complete }">
        <div class="list-item-content">
            <div class="drag-handle text-neutral-400 dark:text-neutral-500" v-if="isOnline">
                <BaseIcon name="heroicons:bars-2" class="w-5 h-5" />
            </div>

            <div class="item-main-content">
                <div class="flex items-center gap-3">
                    <input type="checkbox" :checked="item.is_complete" @change="onCheckboxEvent"
                        class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500" />
                    <div class="flex-1">
                        <span class="text-sm font-medium text-gray-900"
                            :class="{ 'line-through text-gray-500': item.is_complete }">
                            {{ item.name }}
                        </span>
                        <span v-if="item.quantity" class="text-xs text-gray-500 ml-2">
                            Qty: {{ item.quantity }}
                        </span>
                    </div>
                </div>
                <div v-if="claimStatus" class="claim-status-badge">
                    {{ claimStatus }}
                </div>
            </div>

            <div class="item-actions">
                <!-- Claim/Unclaim Buttons -->
                <Button v-if="canClaim" variant="outline" size="sm" @click="handleClaim">
                    Claim
                </Button>
                <Button v-if="canUnclaim" variant="outline" size="sm" @click="handleUnclaim">
                    Unclaim
                </Button>

                <Input v-if="item.is_complete" type="number" :model-value="item.price"
                    @update:modelValue="$emit('update-price', item, $event)" placeholder="0.00" class="w-20" />
                <Button variant="ghost" size="sm" @click="$emit('edit-item', item)" aria-label="Edit Item">
                    <BaseIcon name="heroicons:pencil-square" />
                </Button>
                <!-- Quantity stepper -->
                <div class="flex items-center gap-1 ml-2">
                    <Button variant="outline" size="xs" @click="decreaseQty"
                        :disabled="Number(item.quantity ?? '1') <= 1">
                        <BaseIcon name="heroicons:minus-small" />
                    </Button>
                    <span class="min-w-[1.5rem] text-center text-sm">{{ item.quantity ?? '1' }}</span>
                    <Button variant="outline" size="xs" @click="increaseQty">
                        <BaseIcon name="heroicons:plus-small" />
                    </Button>
                </div>
                <!-- Mark bought button appears when claimed_by_me and not purchased -->
                <Button v-if="showMarkBought" variant="solid" color="success" size="sm" @click="markBought">
                    <BaseIcon name="heroicons:shopping-cart" />
                </Button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, computed } from 'vue';
import type { PropType } from 'vue';
import type { Item } from '@/types/item';
import type { List } from '@/types/list';
import { useListsStore } from '@/stores/listsStore';
import { useAuthStore } from '@/stores/auth';
import { formatDistanceToNow } from 'date-fns';
import Checkbox from '@/components/ui/Switch.vue';
import Button from '@/components/ui/Button.vue';
import Input from '@/components/ui/Input.vue';
import BaseIcon from '@/components/BaseIcon.vue';
import { useSocket } from '@/composables/useSocket';

const props = defineProps({
    item: {
        type: Object as PropType<Item & { swiped?: boolean; }>,
        required: true,
    },
    list: {
        type: Object as PropType<List>,
        required: true,
    },
    isOnline: Boolean,
});

const emit = defineEmits(['delete-item', 'checkbox-change', 'update-price', 'edit-item', 'update-quantity', 'mark-bought']);

const listsStore = useListsStore();
const authStore = useAuthStore();
const currentUser = computed(() => authStore.user);

const canClaim = computed(() => props.list.group_id && !props.item.is_complete && !props.item.claimed_by_user_id);

const canUnclaim = computed(() => {
    return props.item.claimed_by_user_id === currentUser.value?.id;
});

const claimStatus = computed(() => {
    if (!props.item.claimed_by_user) return '';
    const claimer = props.item.claimed_by_user_id === currentUser.value?.id ? 'You' : props.item.claimed_by_user.name;
    const time = props.item.claimed_at ? formatDistanceToNow(new Date(props.item.claimed_at), { addSuffix: true }) : '';
    return `${claimer} claimed this ${time}`;
});

const handleClaim = () => {
    if (!props.list.group_id) return; // Should not happen if button is shown, but good practice
    listsStore.claimItem(props.item.id);
    socket.emit('lists:item:update', { id: props.item.id, action: 'claim' });
};

const handleUnclaim = () => {
    listsStore.unclaimItem(props.item.id);
    socket.emit('lists:item:update', { id: props.item.id, action: 'unclaim' });
};

const socket = useSocket();

const showMarkBought = computed(() => props.item.claimed_by_user_id === currentUser.value?.id && !props.item.is_complete);

const markBought = () => {
    emit('mark-bought', props.item);
    socket.emit('lists:item:update', { id: props.item.id, action: 'bought' });
};

const increaseQty = () => {
    const currentQty = Number(props.item.quantity ?? '1');
    emit('update-quantity', props.item, String(currentQty + 1));
};

const decreaseQty = () => {
    const currentQty = Number(props.item.quantity ?? '1');
    emit('update-quantity', props.item, String(Math.max(1, currentQty - 1)));
};

const onCheckboxEvent = (event: Event) => {
    const target = event.target as HTMLInputElement;
    emit('checkbox-change', props.item, target.checked);
};
</script>

<style scoped>
/* Basic styling to make it look acceptable */
.list-item-wrapper {
    position: relative;
    overflow: hidden;
}

.list-item-content {
    display: flex;
    align-items: center;
    padding: 0.75rem;
    background-color: white;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    margin-bottom: 0.5rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: none;
}

.list-item-delete {
    display: none;
}

.drag-handle {
    cursor: move;
    color: #9ca3af;
    margin-right: 0.75rem;
}

.item-main-content {
    flex-grow: 1;
}

.claim-status-badge {
    font-size: 0.75rem;
    color: #6b7280;
    margin-left: 2.25rem;
    /* Align under checkbox */
    margin-top: 0.25rem;
}

.item-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.price-input {
    width: 80px;
}

.is-complete .item-main-content {
    opacity: 0.6;
}

.is-complete .VCheckbox :deep(label) {
    text-decoration: line-through;
}
</style>