<template>
    <div class="item-composer">
        <!-- Quick Add Bar -->
        <div class="composer-container" :class="{ 'composer-focused': isFocused, 'composer-listening': isListening }">
            <div class="input-section">
                <div class="input-wrapper">
                    <BaseIcon name="heroicons:plus-20-solid" class="add-icon" />
                    <input ref="inputRef" v-model="itemText" type="text"
                        placeholder="Add item... (e.g., 2x Organic Milk)" class="item-input" @focus="handleFocus"
                        @blur="handleBlur" @keydown="handleKeydown" @input="handleInput" autocomplete="off" />
                    <div class="input-actions">
                        <!-- Voice Input Button -->
                        <Button v-if="supportsSpeechRecognition" variant="ghost" size="sm"
                            :class="{ 'listening': isListening }" @click="toggleVoiceInput">
                            <BaseIcon
                                :name="isListening ? 'heroicons:stop-20-solid' : 'heroicons:microphone-20-solid'" />
                        </Button>

                        <!-- Add Button -->
                        <Button variant="solid" color="primary" size="sm" :disabled="!itemText.trim()" @click="addItem">
                            Add
                        </Button>
                    </div>
                </div>

                <!-- Smart Suggestions Dropdown -->
                <Transition name="dropdown">
                    <div v-if="showSuggestions && filteredSuggestions.length > 0" class="suggestions-dropdown">
                        <div class="suggestions-header">
                            <span class="suggestions-title">Suggestions</span>
                            <span class="suggestions-count">{{ filteredSuggestions.length }}</span>
                        </div>
                        <div class="suggestions-list">
                            <button v-for="(suggestion, index) in filteredSuggestions" :key="suggestion.id"
                                :class="['suggestion-item', { 'highlighted': highlightedIndex === index }]"
                                @click="selectSuggestion(suggestion)" @mouseenter="highlightedIndex = index">
                                <div class="suggestion-content">
                                    <div class="suggestion-main">
                                        <span class="suggestion-name">{{ suggestion.name }}</span>
                                        <span v-if="suggestion.brand" class="suggestion-brand">{{ suggestion.brand
                                        }}</span>
                                    </div>
                                    <div class="suggestion-meta">
                                        <span v-if="suggestion.category" class="suggestion-category">{{
                                            suggestion.category }}</span>
                                        <span v-if="suggestion.lastPrice" class="suggestion-price">${{
                                            suggestion.lastPrice }}</span>
                                    </div>
                                </div>
                                <div class="suggestion-stats">
                                    <span class="suggestion-frequency">{{ suggestion.frequency }}x</span>
                                </div>
                            </button>
                        </div>
                    </div>
                </Transition>
            </div>

            <!-- Smart Context Bar -->
            <Transition name="slide-down">
                <div v-if="isFocused && !itemText" class="context-bar">
                    <div class="context-tabs">
                        <button v-for="tab in contextTabs" :key="tab.id"
                            :class="['context-tab', { 'active': activeTab === tab.id }]" @click="activeTab = tab.id">
                            <BaseIcon :name="tab.icon" class="tab-icon" />
                            <span class="tab-label">{{ tab.label }}</span>
                            <span v-if="tab.count" class="tab-count">{{ tab.count }}</span>
                        </button>
                    </div>

                    <div class="context-content">
                        <!-- Recent Items -->
                        <div v-if="activeTab === 'recent'" class="quick-add-grid">
                            <button v-for="item in recentItems" :key="item.id" class="quick-add-chip"
                                @click="selectSuggestion(item)">
                                <span class="chip-text">{{ item.name }}</span>
                                <BaseIcon name="heroicons:plus-20-solid" class="chip-icon" />
                            </button>
                        </div>

                        <!-- Categories -->
                        <div v-else-if="activeTab === 'categories'" class="categories-grid">
                            <button v-for="category in popularCategories" :key="category.id" class="category-chip"
                                @click="setCategory(category)">
                                <BaseIcon :name="category.icon" class="category-icon" />
                                <span class="category-name">{{ category.name }}</span>
                            </button>
                        </div>

                        <!-- Voice Commands -->
                        <div v-else-if="activeTab === 'voice'" class="voice-guide">
                            <div class="voice-examples">
                                <p class="voice-instruction">Try saying:</p>
                                <ul class="voice-commands">
                                    <li>"Add two pounds of ground beef"</li>
                                    <li>"Three bottles of olive oil"</li>
                                    <li>"Organic bananas"</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </Transition>
        </div>

        <!-- Voice Feedback -->
        <Transition name="fade">
            <div v-if="isListening" class="voice-feedback">
                <div class="voice-indicator">
                    <div class="voice-wave"></div>
                    <div class="voice-wave"></div>
                    <div class="voice-wave"></div>
                </div>
                <span class="voice-text">{{ voiceStatus }}</span>
            </div>
        </Transition>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import BaseIcon from '@/components/BaseIcon.vue'
import { Button } from '@/components/ui'

interface ItemSuggestion {
    id: string
    name: string
    brand?: string
    category?: string
    lastPrice?: number
    frequency: number
}

interface Category {
    id: string
    name: string
    icon: string
}

interface Props {
    listId: string
    storeLocation?: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
    'item-added': [item: any]
}>()

// Component state
const inputRef = ref<HTMLInputElement>()
const itemText = ref('')
const isFocused = ref(false)
const isListening = ref(false)
const voiceStatus = ref('Listening...')
const activeTab = ref<'recent' | 'categories' | 'voice'>('recent')
const highlightedIndex = ref(-1)

// Voice recognition basic support check
const supportsSpeechRecognition = computed(() => false) // Simplified for now

// Suggestions and context
const suggestions = ref<ItemSuggestion[]>([])
const showSuggestions = computed(() => isFocused.value && itemText.value.length > 0)

const filteredSuggestions = computed(() => {
    if (!itemText.value) return []

    const searchTerm = itemText.value.toLowerCase()
    return suggestions.value
        .filter(s => s.name.toLowerCase().includes(searchTerm))
        .sort((a, b) => b.frequency - a.frequency)
        .slice(0, 6)
})

const recentItems = computed(() =>
    suggestions.value
        .sort((a, b) => b.frequency - a.frequency)
        .slice(0, 8)
)

const popularCategories = computed<Category[]>(() => [
    { id: 'produce', name: 'Produce', icon: 'heroicons:heart-20-solid' },
    { id: 'dairy', name: 'Dairy', icon: 'heroicons:cube-20-solid' },
    { id: 'meat', name: 'Meat & Seafood', icon: 'heroicons:fire-20-solid' },
    { id: 'pantry', name: 'Pantry', icon: 'heroicons:archive-box-20-solid' },
    { id: 'frozen', name: 'Frozen', icon: 'heroicons:snowflake-20-solid' },
    { id: 'household', name: 'Household', icon: 'heroicons:home-20-solid' }
])

const contextTabs = computed(() => [
    { id: 'recent' as const, label: 'Recent', icon: 'heroicons:clock-20-solid', count: recentItems.value.length },
    { id: 'categories' as const, label: 'Categories', icon: 'heroicons:tag-20-solid' },
    { id: 'voice' as const, label: 'Voice', icon: 'heroicons:microphone-20-solid' }
])

// Event handlers
const handleFocus = () => {
    isFocused.value = true
    loadSuggestions()
}

const handleBlur = () => {
    // Delay to allow clicks on suggestions
    setTimeout(() => {
        isFocused.value = false
        highlightedIndex.value = -1
    }, 200)
}

const handleInput = () => {
    highlightedIndex.value = -1
}

const handleKeydown = (event: KeyboardEvent) => {
    if (!showSuggestions.value) return

    switch (event.key) {
        case 'ArrowDown':
            event.preventDefault()
            highlightedIndex.value = Math.min(
                highlightedIndex.value + 1,
                filteredSuggestions.value.length - 1
            )
            break
        case 'ArrowUp':
            event.preventDefault()
            highlightedIndex.value = Math.max(highlightedIndex.value - 1, -1)
            break
        case 'Enter':
            event.preventDefault()
            if (highlightedIndex.value >= 0) {
                selectSuggestion(filteredSuggestions.value[highlightedIndex.value])
            } else {
                addItem()
            }
            break
        case 'Escape':
            isFocused.value = false
            inputRef.value?.blur()
            break
    }
}

const toggleVoiceInput = () => {
    // Voice input would be implemented here
    console.log('Voice input toggle')
}

const selectSuggestion = (suggestion: ItemSuggestion) => {
    itemText.value = suggestion.name
    addItem()
}

const setCategory = (category: Category) => {
    // Could set a category filter or prefix
    inputRef.value?.focus()
}

const addItem = async () => {
    if (!itemText.value.trim()) return

    const itemData = {
        name: itemText.value.trim(),
        quantity: 1,
        list_id: props.listId,
        claimed_by_user_id: null
    }

    // Emit the item for parent to handle
    emit('item-added', itemData)
    itemText.value = ''

    // Update suggestions frequency
    updateSuggestionFrequency(itemData.name)
}

const loadSuggestions = async () => {
    // Mock suggestions for now
    suggestions.value = [
        { id: '1', name: 'Organic Milk', category: 'Dairy', frequency: 5, lastPrice: 4.99 },
        { id: '2', name: 'Bananas', category: 'Produce', frequency: 8, lastPrice: 2.49 },
        { id: '3', name: 'Bread', category: 'Bakery', frequency: 3, lastPrice: 3.49 },
        { id: '4', name: 'Eggs', category: 'Dairy', frequency: 4, lastPrice: 5.99 },
        { id: '5', name: 'Chicken Breast', category: 'Meat', frequency: 2, lastPrice: 8.99 }
    ]
}

const updateSuggestionFrequency = (itemName: string) => {
    const existing = suggestions.value.find(s => s.name.toLowerCase() === itemName.toLowerCase())
    if (existing) {
        existing.frequency++
    } else {
        suggestions.value.push({
            id: `suggestion-${Date.now()}`,
            name: itemName,
            frequency: 1
        })
    }
}

// Lifecycle
onMounted(() => {
    loadSuggestions()
})
</script>

<style scoped>
.item-composer {
    @apply relative;
}

.composer-container {
    @apply bg-surface-primary border border-border-primary rounded-lg transition-all duration-micro;
    @apply hover:border-border-primary-hover;
}

.composer-focused {
    @apply border-primary-500 ring-2 ring-primary-500/20;
}

.composer-listening {
    @apply border-accent-500 ring-2 ring-accent-500/20;
}

.input-section {
    @apply relative;
}

.input-wrapper {
    @apply flex items-center gap-3 p-4;
}

.add-icon {
    @apply w-5 h-5 text-text-secondary flex-shrink-0;
}

.item-input {
    @apply flex-1 bg-transparent border-0 outline-none text-text-primary placeholder-text-tertiary;
    @apply text-sm leading-5;
}

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

.listening {
    @apply text-accent-500 bg-accent-50 dark:bg-accent-500/10;
}

/* Suggestions dropdown */
.suggestions-dropdown {
    @apply absolute top-full left-0 right-0 bg-surface-primary border border-border-primary rounded-lg shadow-strong;
    @apply mt-2 py-2 z-50 max-h-80 overflow-y-auto;
}

.suggestions-header {
    @apply flex items-center justify-between px-4 py-2 border-b border-border-primary;
}

.suggestions-title {
    @apply text-xs font-medium text-text-secondary uppercase tracking-wider;
}

.suggestions-count {
    @apply text-xs text-text-tertiary;
}

.suggestion-item {
    @apply w-full flex items-center justify-between px-4 py-3 hover:bg-surface-secondary;
    @apply transition-colors duration-micro cursor-pointer;
}

.suggestion-item.highlighted {
    @apply bg-primary-50 dark:bg-primary-500/10;
}

.suggestion-content {
    @apply flex-1 min-w-0;
}

.suggestion-main {
    @apply flex items-center gap-2 mb-1;
}

.suggestion-name {
    @apply font-medium text-text-primary truncate;
}

.suggestion-brand {
    @apply text-xs text-text-secondary bg-surface-tertiary px-2 py-0.5 rounded;
}

.suggestion-meta {
    @apply flex items-center gap-3 text-xs text-text-tertiary;
}

.suggestion-stats {
    @apply text-xs text-text-tertiary font-medium;
}

/* Context bar */
.context-bar {
    @apply border-t border-border-primary bg-surface-secondary;
}

.context-tabs {
    @apply flex border-b border-border-primary;
}

.context-tab {
    @apply flex items-center gap-2 px-4 py-3 text-sm font-medium text-text-secondary;
    @apply hover:text-text-primary hover:bg-surface-primary transition-colors duration-micro;
}

.context-tab.active {
    @apply text-primary-600 bg-primary-50 border-b-2 border-primary-500;
}

.tab-count {
    @apply text-xs bg-surface-tertiary text-text-tertiary px-1.5 py-0.5 rounded;
}

.context-content {
    @apply p-4;
}

/* Quick add chips */
.quick-add-grid {
    @apply grid grid-cols-2 sm:grid-cols-4 gap-2;
}

.quick-add-chip {
    @apply flex items-center justify-between px-3 py-2 bg-surface-primary border border-border-primary;
    @apply rounded-md hover:border-primary-300 hover:bg-primary-50 transition-colors duration-micro;
}

.chip-text {
    @apply text-sm text-text-primary truncate;
}

.chip-icon {
    @apply w-4 h-4 text-text-tertiary ml-2;
}

/* Categories */
.categories-grid {
    @apply grid grid-cols-3 sm:grid-cols-6 gap-3;
}

.category-chip {
    @apply flex flex-col items-center gap-2 p-3 bg-surface-primary border border-border-primary;
    @apply rounded-lg hover:border-primary-300 hover:bg-primary-50 transition-colors duration-micro;
}

.category-icon {
    @apply w-6 h-6 text-text-secondary;
}

.category-name {
    @apply text-xs font-medium text-text-primary text-center;
}

/* Voice feedback */
.voice-feedback {
    @apply flex items-center gap-3 mt-4 p-4 bg-accent-50 dark:bg-accent-500/10 rounded-lg;
}

.voice-indicator {
    @apply flex items-center gap-1;
}

.voice-wave {
    @apply w-1 h-4 bg-accent-500 rounded-full;
    animation: voice-pulse 1.5s ease-in-out infinite;
}

.voice-wave:nth-child(2) {
    animation-delay: 0.2s;
}

.voice-wave:nth-child(3) {
    animation-delay: 0.4s;
}

.voice-text {
    @apply text-sm font-medium text-accent-700 dark:text-accent-300;
}

/* Voice guide */
.voice-guide {
    @apply text-center;
}

.voice-instruction {
    @apply text-sm font-medium text-text-primary mb-3;
}

.voice-commands {
    @apply text-sm text-text-secondary space-y-1;
}

/* Animations */
.dropdown-enter-active,
.dropdown-leave-active {
    @apply transition-all duration-200;
}

.dropdown-enter-from,
.dropdown-leave-to {
    @apply opacity-0 transform scale-95;
}

.slide-down-enter-active,
.slide-down-leave-active {
    @apply transition-all duration-300;
}

.slide-down-enter-from,
.slide-down-leave-to {
    @apply opacity-0 transform -translate-y-2;
}

.fade-enter-active,
.fade-leave-active {
    @apply transition-opacity duration-200;
}

.fade-enter-from,
.fade-leave-to {
    @apply opacity-0;
}

@keyframes voice-pulse {

    0%,
    100% {
        height: 1rem;
    }

    50% {
        height: 1.5rem;
    }
}
</style>