<template>
    <div class="foto-first-step-3">
        <div class="step-header mb-4">
            <h4 class="mb-2">Item Details Entry</h4>
            <p class="text-muted">Enter details for each photographed item to complete the inventory import.</p>
        </div>

        <!-- Progress Indicator -->
        <div class="progress-indicator mb-4">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0">Item Progress</h6>
                <span class="badge bg-info">{{ currentItemIndex + 1 }} of {{ totalItems }}</span>
            </div>
            <div class="progress mb-2" style="height: 8px;">
                <div
                    class="progress-bar bg-info"
                    :style="{ width: itemProgressPercentage + '%' }"
                ></div>
            </div>
        </div>

        <!-- Current Item Display -->
        <div v-if="currentItem" class="current-item mb-4">
            <div class="row">
                <!-- Image Preview -->
                <div class="col-md-4">
                    <div class="card">
                        <img :src="currentItem.processedUrl || currentItem.preview" class="card-img-top item-image" alt="Current item">
                        <div class="card-body p-2">
                            <small class="text-muted">{{ currentItem.name }}</small>
                        </div>
                    </div>
                </div>

                <!-- Item Details Form -->
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">Item Details</h6>
                        </div>
                        <div class="card-body">
                            <form @submit.prevent="saveCurrentItem">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Item Name *</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            v-model="currentItemDetails.name"
                                            required
                                            placeholder="Enter item name"
                                        >
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Category</label>
                                        <select class="form-select" v-model="currentItemDetails.category">
                                            <option value="">Select category...</option>
                                            <option value="tools">Tools</option>
                                            <option value="electronics">Electronics</option>
                                            <option value="hardware">Hardware</option>
                                            <option value="materials">Materials</option>
                                            <option value="other">Other</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Quantity</label>
                                        <input
                                            type="number"
                                            class="form-control"
                                            v-model.number="currentItemDetails.quantity"
                                            min="1"
                                            placeholder="1"
                                        >
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Unit</label>
                                        <select class="form-select" v-model="currentItemDetails.unit">
                                            <option value="piece">Piece</option>
                                            <option value="set">Set</option>
                                            <option value="box">Box</option>
                                            <option value="pack">Pack</option>
                                            <option value="meter">Meter</option>
                                            <option value="kilogram">Kilogram</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Condition</label>
                                        <select class="form-select" v-model="currentItemDetails.condition">
                                            <option value="new">New</option>
                                            <option value="excellent">Excellent</option>
                                            <option value="good">Good</option>
                                            <option value="fair">Fair</option>
                                            <option value="poor">Poor</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Description</label>
                                    <textarea
                                        class="form-control"
                                        rows="3"
                                        v-model="currentItemDetails.description"
                                        placeholder="Optional description or notes"
                                    ></textarea>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Storage Location</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        v-model="currentItemDetails.location"
                                        placeholder="e.g., Shelf A, Drawer 3, etc."
                                    >
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Purchase Price</label>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input
                                                type="number"
                                                class="form-control"
                                                v-model.number="currentItemDetails.purchase_price"
                                                step="0.01"
                                                min="0"
                                                placeholder="0.00"
                                            >
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Estimated Value</label>
                                        <div class="input-group">
                                            <span class="input-group-text">$</span>
                                            <input
                                                type="number"
                                                class="form-control"
                                                v-model.number="currentItemDetails.estimated_value"
                                                step="0.01"
                                                min="0"
                                                placeholder="0.00"
                                            >
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Item Navigation -->
        <div class="item-navigation mb-4">
            <div class="d-flex justify-content-between align-items-center">
                <button
                    class="btn btn-outline-secondary"
                    @click="previousItem"
                    :disabled="currentItemIndex === 0"
                >
                    <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                    Previous Item
                </button>

                <div class="btn-group">
                    <button class="btn btn-primary" @click="saveCurrentItem">
                        <b-icon-check class="me-1"></b-icon-check>
                        Save Item
                    </button>
                    <button class="btn btn-outline-primary" @click="skipCurrentItem">
                        <b-icon-skip-forward class="me-1"></b-icon-skip-forward>
                        Skip
                    </button>
                </div>

                <button
                    class="btn btn-outline-secondary"
                    @click="nextItem"
                    :disabled="currentItemIndex >= totalItems - 1"
                >
                    Next Item
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>

        <!-- Completed Items Summary -->
        <div v-if="completedItems.length > 0" class="completed-items mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Completed Items ({{ completedItems.length }})</h6>
                    <button class="btn btn-sm btn-outline-info" @click="showCompleted = !showCompleted">
                        <b-icon-eye v-if="!showCompleted"></b-icon-eye>
                        <b-icon-eye-slash v-else></b-icon-eye-slash>
                        {{ showCompleted ? 'Hide' : 'Show' }}
                    </button>
                </div>
                <div v-if="showCompleted" class="card-body">
                    <div class="row">
                        <div v-for="(item, index) in completedItems" :key="index" class="col-sm-6 col-md-4 col-lg-3 mb-2">
                            <div class="d-flex align-items-center">
                                <img :src="item.image.processedUrl || item.image.preview" class="completed-item-thumb me-2" alt="Item">
                                <div class="flex-grow-1">
                                    <div class="fw-bold small">{{ item.details.name }}</div>
                                    <div class="text-muted small">{{ item.details.category || 'No category' }}</div>
                                </div>
                                <button class="btn btn-sm btn-outline-secondary" @click="editItem(index)">
                                    <b-icon-pencil></b-icon-pencil>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation -->
        <div class="step-navigation d-flex justify-content-between">
            <button class="btn btn-outline-secondary" @click="$emit('prev')">
                <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                Previous
            </button>
            <button
                class="btn btn-success"
                @click="proceedToNext"
                :disabled="completedItems.length === 0"
            >
                Next: Complete Import ({{ completedItems.length }} items)
                <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
            </button>
        </div>
    </div>
</template>

<script>
import * as BIcons from "bootstrap-icons-vue";

export default {
    name: 'FotoFirstStep3',
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            currentItemIndex: 0,
            currentItemDetails: this.getDefaultItemDetails(),
            completedItems: [],
            showCompleted: false
        }
    },
    computed: {
        availableItems() {
            return this.payload.processed_images || this.payload.photos || [];
        },
        totalItems() {
            return this.availableItems.length;
        },
        currentItem() {
            return this.availableItems[this.currentItemIndex] || null;
        },
        itemProgressPercentage() {
            return this.totalItems > 0 ? (this.completedItems.length / this.totalItems) * 100 : 0;
        }
    },
    mounted() {
        // Load existing completed items
        if (this.payload.completed_items) {
            this.completedItems = [...this.payload.completed_items];
        }

        // Load current item details if resuming
        if (this.payload.current_item_details) {
            this.currentItemDetails = { ...this.payload.current_item_details };
        }

        // Load current item index if resuming
        if (this.payload.current_item_index !== undefined) {
            this.currentItemIndex = this.payload.current_item_index;
        }
    },
    methods: {
        getDefaultItemDetails() {
            return {
                name: '',
                category: '',
                quantity: 1,
                unit: 'piece',
                condition: 'good',
                description: '',
                location: '',
                purchase_price: null,
                estimated_value: null
            };
        },

        saveCurrentItem() {
            if (!this.currentItemDetails.name.trim()) {
                alert('Please enter an item name before saving.');
                return;
            }

            const itemData = {
                image: this.currentItem,
                details: { ...this.currentItemDetails },
                saved_at: new Date().toISOString()
            };

            // Check if we're editing an existing item
            const existingIndex = this.completedItems.findIndex(item =>
                item.image === this.currentItem
            );

            if (existingIndex >= 0) {
                this.completedItems.splice(existingIndex, 1, itemData);
            } else {
                this.completedItems.push(itemData);
            }

            this.nextItem();
            this.updatePayload();
        },

        skipCurrentItem() {
            this.nextItem();
        },

        nextItem() {
            if (this.currentItemIndex < this.totalItems - 1) {
                this.currentItemIndex++;
                this.currentItemDetails = this.getDefaultItemDetails();
            }
        },

        previousItem() {
            if (this.currentItemIndex > 0) {
                this.currentItemIndex--;

                // Load details if this item was already completed
                const existingItem = this.completedItems.find(item =>
                    item.image === this.currentItem
                );

                if (existingItem) {
                    this.currentItemDetails = { ...existingItem.details };
                } else {
                    this.currentItemDetails = this.getDefaultItemDetails();
                }
            }
        },

        editItem(index) {
            const item = this.completedItems[index];
            // Find the item index in available items
            const itemIndex = this.availableItems.findIndex(img => img === item.image);
            if (itemIndex >= 0) {
                this.currentItemIndex = itemIndex;
                this.currentItemDetails = { ...item.details };
            }
        },

        updatePayload() {
            this.$emit('update', {
                completed_items: this.completedItems,
                current_item_details: this.currentItemDetails,
                current_item_index: this.currentItemIndex
            });
        },

        proceedToNext() {
            if (this.completedItems.length === 0) {
                alert('Please complete at least one item before proceeding.');
                return;
            }

            this.updatePayload();
            this.$emit('next');
        }
    }
}
</script>

<style scoped>
.item-image {
    height: 300px;
    object-fit: cover;
}

.completed-item-thumb {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

.item-navigation {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 8px;
}
</style>
