<template>
    <Dialog v-model="open" size="md" class="z-50">
        <div class="receipt-scanner-modal">
            <header class="modal-header">
                <BaseIcon name="heroicons:receipt-percent" class="header-icon" />
                <Heading :level="3">Scan Receipt</Heading>
                <Button variant="ghost" size="sm" @click="closeModal" class="close-btn">
                    <BaseIcon name="heroicons:x-mark" />
                </Button>
            </header>

            <main class="modal-content">
                <div v-if="!imagePreview && !loading" class="upload-section">
                    <label class="upload-label" @dragover.prevent @drop.prevent="handleDrop">
                        <BaseIcon name="heroicons:photo" class="upload-icon" />
                        <span>Drag & drop or click to upload a receipt image (JPG, PNG, WEBP)</span>
                        <input type="file" accept="image/*" @change="handleFileChange" hidden />
                    </label>
                    <p class="upload-help">Max size: 5MB. Only images are supported.</p>
                </div>

                <div v-if="imagePreview && !loading" class="preview-section">
                    <img :src="imagePreview" alt="Receipt Preview" class="receipt-preview" />
                    <Button variant="outline" size="sm" @click="removeImage" class="remove-btn">
                        <BaseIcon name="heroicons:trash" />
                        Remove
                    </Button>
                </div>

                <div v-if="loading" class="loading-section">
                    <Spinner size="lg" />
                    <p class="loading-text">Extracting items from your receipt…</p>
                </div>

                <div v-if="extractedItems.length > 0 && !loading" class="results-section">
                    <h4 class="results-title">Extracted Items</h4>
                    <div class="items-list">
                        <label v-for="(item, idx) in extractedItems" :key="idx" class="item-row">
                            <input type="checkbox" v-model="selectedItems" :value="item" />
                            <span>{{ item }}</span>
                        </label>
                    </div>
                </div>

                <Alert v-if="error" type="error" :message="error" class="mt-4" />
            </main>

            <footer class="modal-footer">
                <Button variant="outline" @click="closeModal">Cancel</Button>
                <Button color="primary" :disabled="selectedItems.length === 0" @click="addSelectedItems">
                    <BaseIcon name="heroicons:plus-circle" />
                    Add Selected Items
                </Button>
            </footer>
        </div>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Dialog, Heading, Button, Alert, Spinner } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { apiClient } from '@/services/api'

const open = defineModel<boolean>('modelValue', { default: false })
const emit = defineEmits<{ (e: 'add', items: string[]): void }>()

const imageFile = ref<File | null>(null)
const imagePreview = ref<string | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const extractedItems = ref<string[]>([])
const selectedItems = ref<string[]>([])

function handleFileChange(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
        if (!file.type.startsWith('image/')) {
            error.value = 'Only image files are supported.'
            return
        }
        if (file.size > 5 * 1024 * 1024) {
            error.value = 'File is too large (max 5MB).'
            return
        }
        imageFile.value = file
        error.value = null
        const reader = new FileReader()
        reader.onload = (ev) => {
            imagePreview.value = ev.target?.result as string
        }
        reader.readAsDataURL(file)
        extractedItems.value = []
        selectedItems.value = []
        uploadImage()
    }
}

function handleDrop(e: DragEvent) {
    const file = e.dataTransfer?.files?.[0]
    if (file) {
        handleFileChange({ target: { files: [file] } } as any)
    }
}

function removeImage() {
    imageFile.value = null
    imagePreview.value = null
    extractedItems.value = []
    selectedItems.value = []
    error.value = null
}

async function uploadImage() {
    if (!imageFile.value) return
    loading.value = true
    error.value = null
    extractedItems.value = []
    selectedItems.value = []
    try {
        const formData = new FormData()
        formData.append('image_file', imageFile.value)
        const { data } = await apiClient.post('/api/v1/ocr/extract-items', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        extractedItems.value = data.extracted_items || []
        selectedItems.value = [...extractedItems.value]
    } catch (err: any) {
        error.value = err?.response?.data?.detail || 'Failed to extract items from receipt.'
    } finally {
        loading.value = false
    }
}

function addSelectedItems() {
    emit('add', selectedItems.value)
    closeModal()
}

function closeModal() {
    open.value = false
    removeImage()
    error.value = null
}

watch(open, (val) => {
    if (!val) removeImage()
})
</script>

<style scoped>
.receipt-scanner-modal {
    @apply bg-surface-primary rounded-lg w-full max-w-md overflow-hidden flex flex-col;
}

.modal-header {
    @apply flex items-center gap-4 p-6 border-b border-border-primary bg-surface-soft relative;
}

.header-icon {
    @apply w-8 h-8 text-primary-500;
}

.close-btn {
    @apply absolute right-4 top-4;
}

.modal-content {
    @apply flex-1 p-6 space-y-6;
}

.upload-section {
    @apply flex flex-col items-center justify-center gap-4;
}

.upload-label {
    @apply flex flex-col items-center gap-2 p-8 border-2 border-dashed border-border-secondary rounded-lg cursor-pointer transition-colors duration-200 hover:border-primary-300 hover:bg-surface-soft;
}

.upload-icon {
    @apply w-12 h-12 text-text-tertiary;
}

.upload-help {
    @apply text-sm text-text-secondary;
}

.preview-section {
    @apply flex flex-col items-center gap-3;
}

.receipt-preview {
    @apply w-64 max-h-64 object-contain rounded-lg shadow;
}

.remove-btn {
    @apply mt-2;
}

.loading-section {
    @apply flex flex-col items-center gap-4;
}

.loading-text {
    @apply text-text-secondary;
}

.results-section {
    @apply mt-4;
}

.results-title {
    @apply text-lg font-semibold text-text-primary mb-2;
}

.items-list {
    @apply flex flex-col gap-2;
}

.item-row {
    @apply flex items-center gap-3 p-2 rounded hover:bg-surface-soft transition-colors duration-150;
}

.modal-footer {
    @apply flex items-center justify-end gap-4 p-6 border-t border-border-primary bg-surface-soft;
}
</style>