<template>
    <div class="bulk-import-step-6">
        <div class="step-header mb-4">
            <h4 class="mb-2">Import Items</h4>
            <p class="text-muted">
                Create inventory items from the rows parsed in the File Upload step.
                The file itself was never sent to the server - only these structured
                item rows are.
            </p>
        </div>

        <div v-if="!results" class="card mb-4">
            <div class="card-body text-center py-4">
                <p class="mb-3">
                    <strong>{{ items.length }}</strong> item(s) ready to import.
                </p>
                <button class="btn btn-primary" :disabled="importing || items.length === 0" @click="runImport">
                    <span v-if="importing" class="spinner-border spinner-border-sm me-2"></span>
                    Import {{ items.length }} item(s)
                </button>
                <div v-if="error" class="alert alert-danger mt-3 mb-0">{{ error }}</div>
            </div>
        </div>

        <div v-else class="card mb-4">
            <div class="card-body">
                <h6 class="mb-2">Import complete</h6>
                <p class="mb-2">
                    <span class="badge bg-success me-2">{{ results.created_count }} created</span>
                    <span v-if="results.errors && results.errors.length" class="badge bg-warning text-dark">
                        {{ results.errors.length }} issue(s)
                    </span>
                </p>
                <ul v-if="results.errors && results.errors.length" class="small text-muted mb-0">
                    <li v-for="(err, index) in results.errors" :key="index">{{ err }}</li>
                </ul>
            </div>
        </div>

        <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-primary" :disabled="!results" @click="$emit('next')">
                Next: Generate Report
                <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
            </button>
        </div>
    </div>
</template>

<script>
import * as BIcons from "bootstrap-icons-vue";
import { mapActions } from 'vuex';

export default {
    name: 'BulkImportStep6',
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            importing: false,
            error: null,
            results: this.payload.import_results || null
        }
    },
    computed: {
        items() {
            return this.payload.items || [];
        }
    },
    methods: {
        ...mapActions(['createInventoryItem']),
        async runImport() {
            this.importing = true;
            this.error = null;
            const created_item_ids = [];
            const errors = [];
            // Items were fully parsed client-side (File Upload step). The backend
            // never sees the source file or any bulk-import-specific endpoint -
            // each row is created through the same generic
            // POST /api/inventory_items/ endpoint any other client would use.
            for (const [index, row] of this.items.entries()) {
                if (!row.name) {
                    errors.push(`Row ${index + 1}: missing required "name" field, skipped.`);
                    continue;
                }
                try {
                    const created = await this.createInventoryItem({
                        name: row.name,
                        description: row.description || '',
                        owned_quantity: parseInt(row.quantity) || 1,
                        ...(row.category ? {category: row.category} : {})
                    });
                    created_item_ids.push(created.id);
                } catch (err) {
                    console.error('Failed to create item:', row, err);
                    errors.push(`Row ${index + 1} ("${row.name}"): failed to create.`);
                }
            }
            this.results = {created_item_ids, created_count: created_item_ids.length, errors};
            this.$emit('update', {import_results: this.results});
            this.importing = false;
        }
    }
}
</script>

