<template>
    <div class="bulk-item-import-workflow">
        <!-- Step 1: File Upload -->
        <div v-if="step === '1'" class="bulk-import-step-1">
            <div class="step-header mb-4">
                <h4 class="mb-2">File Upload</h4>
                <p class="text-muted">Upload your CSV or Excel file containing item data for bulk import.</p>
            </div>

            <!-- File Upload Area -->
            <div class="upload-section mb-4">
                <div class="card">
                    <div class="card-body">
                        <div v-if="!uploadedFile" class="upload-dropzone text-center py-5"
                             @dragover.prevent
                             @dragenter.prevent
                             @drop.prevent="handleFileDrop"
                             :class="{ 'dragover': isDragOver }"
                             @dragenter="isDragOver = true"
                             @dragleave="isDragOver = false">

                            <b-icon-cloud-upload class="text-primary mb-3" style="font-size: 4rem;"></b-icon-cloud-upload>
                            <h5 class="mb-3">Upload Your Data File</h5>
                            <p class="text-muted mb-4">
                                Drag and drop your CSV or Excel file here, or click to browse
                            </p>

                            <input
                                type="file"
                                ref="fileInput"
                                accept=".csv,.xlsx,.xls"
                                @change="handleFileSelect"
                                class="d-none"
                            />

                            <div class="mb-3">
                                <button class="btn btn-primary btn-lg me-2" @click="$refs.fileInput.click()">
                                    <b-icon-folder-open class="me-2"></b-icon-folder-open>
                                    Choose File
                                </button>
                                <button class="btn btn-outline-info" @click="downloadTemplate">
                                    <b-icon-download class="me-2"></b-icon-download>
                                    Download Template
                                </button>
                            </div>

                            <div class="supported-formats">
                                <small class="text-muted">
                                    Supported formats: CSV (.csv), Excel (.xlsx, .xls)
                                </small>
                            </div>
                        </div>

                        <!-- File Info Display -->
                        <div v-else class="file-info">
                            <div class="d-flex align-items-center justify-content-between mb-3">
                                <div class="d-flex align-items-center">
                                    <b-icon-file-earmark-spreadsheet class="text-success me-3" style="font-size: 2rem;"></b-icon-file-earmark-spreadsheet>
                                    <div>
                                        <h6 class="mb-1">{{ uploadedFile.name }}</h6>
                                        <small class="text-muted">
                                            {{ formatFileSize(uploadedFile.size) }} •
                                            {{ getFileType(uploadedFile.name) }} •
                                            Uploaded {{ formatDateTime(uploadTime) }}
                                        </small>
                                    </div>
                                </div>
                                <button class="btn btn-outline-danger btn-sm" @click="removeFile">
                                    <b-icon-trash></b-icon-trash>
                                    Remove
                                </button>
                            </div>

                            <!-- File Analysis Results -->
                            <div v-if="fileAnalysis" class="file-analysis">
                                <div class="row">
                                    <div class="col-md-3 mb-2">
                                        <div class="text-center">
                                            <h4 class="text-primary mb-1">{{ fileAnalysis.totalRows }}</h4>
                                            <small class="text-muted">Total Rows</small>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <div class="text-center">
                                            <h4 class="text-info mb-1">{{ fileAnalysis.totalColumns }}</h4>
                                            <small class="text-muted">Columns</small>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <div class="text-center">
                                            <h4 class="text-success mb-1">{{ fileAnalysis.validRows }}</h4>
                                            <small class="text-muted">Valid Rows</small>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <div class="text-center">
                                            <h4 class="text-warning mb-1">{{ fileAnalysis.errorRows }}</h4>
                                            <small class="text-muted">Issues Found</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- File Processing Status -->
            <div v-if="processingFile" class="processing-status mb-4">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="spinner-border text-primary me-3" role="status"></div>
                            <div>
                                <h6 class="mb-1">Processing file...</h6>
                                <p class="text-muted mb-0">{{ processingStatus }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Column Mapping -->
            <div v-if="fileAnalysis && !processingFile" class="column-mapping mb-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Column Mapping</h6>
                        <small class="text-muted">Map your file columns to system fields</small>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div v-for="field in requiredFields" :key="field.key" class="col-md-6 mb-3">
                                <label class="form-label">
                                    {{ field.label }}
                                    <span v-if="field.required" class="text-danger">*</span>
                                </label>
                                <select class="form-select" v-model="columnMapping[field.key]">
                                    <option value="">Select column...</option>
                                    <option v-for="column in detectedColumns" :key="column" :value="column">
                                        {{ column }}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Data Preview -->
            <div v-if="previewData.length > 0" class="data-preview mb-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Data Preview</h6>
                        <small class="text-muted">First 5 rows of your data</small>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th v-for="column in detectedColumns" :key="column">{{ column }}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(row, index) in previewData.slice(0, 5)" :key="index">
                                        <td v-for="column in detectedColumns" :key="column">
                                            {{ row[column] || '-' }}
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Navigation -->
            <div class="step-navigation d-flex justify-content-between">
                <div></div>
                <button
                    class="btn btn-primary"
                    @click="proceedFromStep1"
                    :disabled="!canProceedFromStep1"
                >
                    Next: Parse Data
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>

        <!-- Step 6: Import Items -->
        <div v-else-if="step === '6'" 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="!importResults" 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="importError" class="alert alert-danger mt-3 mb-0">{{ importError }}</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">{{ importResults.created_count }} created</span>
                        <span v-if="importResults.errors && importResults.errors.length" class="badge bg-warning text-dark">
                            {{ importResults.errors.length }} issue(s)
                        </span>
                    </p>
                    <ul v-if="importResults.errors && importResults.errors.length" class="small text-muted mb-0">
                        <li v-for="(err, index) in importResults.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="!importResults" @click="$emit('next')">
                    Next: Generate Report
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>

        <!-- Fallback for not-yet-implemented steps (2-5, 7) -->
        <div v-else class="text-center py-5">
            <b-icon-gear class="text-muted mb-3" style="font-size: 3rem;"></b-icon-gear>
            <h5 class="text-muted">{{ currentStepDefinition?.name || `Step ${step}` }}</h5>
            <p class="text-muted">{{ currentStepDefinition?.description || 'This step is in progress.' }}</p>

            <div class="mt-4">
                <button class="btn btn-outline-secondary me-2" @click="$emit('prev')">
                    <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                    Previous
                </button>
                <button class="btn btn-primary" @click="$emit('next')">
                    Next
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>
    </div>
</template>

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

// Implements every step of 'import-items'; steps 2-5,7 use a generic placeholder. See docs/implementation.md#bulk-item-import-workflow.
export default {
    name: 'BulkItemImportWorkflow',
    // Co-located workflow metadata, single source of truth per workflow type. See docs/implementation.md#workflow-meta-co-location.
    meta: {
        slug: 'import-items',
        title: 'Bulk Item Import',
        category: 'Data Management',
        description: 'Import multiple inventory items from CSV or Excel files with validation.',
        icons: ['b-icon-upload', 'b-icon-file-earmark-spreadsheet', 'b-icon-list-check'],
        estimatedDuration: '20-60 minutes',
        stepDefinitions: [
            { step: '1', name: 'File Upload', description: 'Upload CSV or Excel file' },
            { step: '2', name: 'Parse Data', description: 'Parse and analyze file contents' },
            { step: '3', name: 'Validate Format', description: 'Validate data format and structure' },
            { step: '4', name: 'Data Validation', description: 'Validate individual item data' },
            { step: '5', name: 'Conflict Resolution', description: 'Resolve any data conflicts' },
            { step: '6', name: 'Import Items', description: 'Import validated items into system' },
            { step: '7', name: 'Generate Report', description: 'Generate import summary report' }
        ],
        getInitialPayload() {
            return {
                import_options: {
                    file_type: null,
                    skip_duplicates: true,
                    update_existing: false,
                    validate_required_fields: true
                },
                mapping: {},
                validation_results: []
            };
        }
    },
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            // Step 1: file upload
            uploadedFile: null,
            uploadTime: null,
            processingFile: false,
            processingStatus: '',
            isDragOver: false,
            fileAnalysis: null,
            detectedColumns: [],
            parsedRows: [],
            previewData: [],
            columnMapping: {},
            requiredFields: [
                { key: 'name', label: 'Item Name', required: true },
                { key: 'category', label: 'Category', required: false },
                { key: 'quantity', label: 'Quantity', required: false },
                { key: 'unit', label: 'Unit', required: false },
                { key: 'description', label: 'Description', required: false },
                { key: 'location', label: 'Storage Location', required: false },
                { key: 'purchase_price', label: 'Purchase Price', required: false },
                { key: 'estimated_value', label: 'Estimated Value', required: false }
            ],

            // Step 6: import items
            importing: false,
            importError: null,
            importResults: this.payload.import_results || null
        }
    },
    computed: {
        canProceedFromStep1() {
            return this.uploadedFile && this.fileAnalysis && this.columnMapping.name;
        },
        items() {
            return this.payload.items || [];
        },
        currentStepDefinition() {
            return this.$options.meta.stepDefinitions.find(s => s.step === this.step);
        }
    },
    mounted() {
        // Step 1: load existing data if resuming
        if (this.payload.file_name) {
            this.uploadTime = this.payload.upload_time;
            this.fileAnalysis = this.payload.file_analysis;
            this.detectedColumns = this.payload.detected_columns || [];
            this.parsedRows = this.payload.parsed_rows || [];
            this.previewData = this.payload.preview_data || [];
            this.columnMapping = this.payload.column_mapping || {};
        }
    },
    methods: {
        ...mapActions(['createInventoryItem']),

        // --- Step 1: File upload ---
        handleFileDrop(event) {
            this.isDragOver = false;
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                this.processFile(files[0]);
            }
        },

        handleFileSelect(event) {
            const files = event.target.files;
            if (files.length > 0) {
                this.processFile(files[0]);
            }
        },

        async processFile(file) {
            if (!this.isValidFileType(file)) {
                alert('Please upload a CSV or Excel file (.csv, .xlsx, .xls)');
                return;
            }

            this.uploadedFile = file;
            this.uploadTime = new Date().toISOString();
            this.processingFile = true;
            this.processingStatus = 'Reading file...';

            try {
                await this.analyzeFile(file);
                this.processingStatus = 'Analyzing data structure...';
                await new Promise(resolve => setTimeout(resolve, 1000));

                this.processingStatus = 'Generating preview...';
                await new Promise(resolve => setTimeout(resolve, 500));

                this.updateStep1Payload();
            } catch (error) {
                console.error('Error processing file:', error);
                alert('Error processing file. Please try again.');
                this.removeFile();
            } finally {
                this.processingFile = false;
                this.processingStatus = '';
            }
        },

        async analyzeFile(file) {
            // Parsing happens entirely client-side; the backend only ever sees the resulting `items` list.
            if (file.name.endsWith('.csv')) {
                const text = await file.text();
                this.parsedRows = this.parseCsv(text);
            } else {
                // Mock implementation; a real Excel parser would use a library like SheetJS.
                this.detectedColumns = ['Name', 'Category', 'Quantity', 'Unit', 'Description'];
                this.parsedRows = [
                    { Name: 'Sample Item 1', Category: 'Tools', Quantity: '1', Unit: 'piece', Description: 'Sample description' },
                    { Name: 'Sample Item 2', Category: 'Hardware', Quantity: '5', Unit: 'box', Description: 'Another sample' }
                ];
            }

            this.previewData = this.parsedRows.slice(0, 5);
            this.fileAnalysis = {
                totalRows: this.parsedRows.length,
                totalColumns: this.detectedColumns.length,
                validRows: this.parsedRows.length,
                errorRows: 0
            };

            this.autoMapColumns();
        },

        // Simple CSV parser: no external dependency, entirely client-side.
        parseCsv(text) {
            const lines = text.split('\n').filter(line => line.trim());
            if (lines.length === 0) {
                this.detectedColumns = [];
                return [];
            }
            const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''));
            this.detectedColumns = headers;
            return lines.slice(1).map(line => {
                const values = line.split(',').map(v => v.trim().replace(/"/g, ''));
                const row = {};
                headers.forEach((header, index) => {
                    row[header] = values[index] || '';
                });
                return row;
            });
        },

        // Converts parsed rows + column mapping into item dicts for the "Import Items" step.
        buildItemsFromMapping() {
            return this.parsedRows.map(row => ({
                name: this.columnMapping.name ? row[this.columnMapping.name] : '',
                description: this.columnMapping.description ? row[this.columnMapping.description] : '',
                category: this.columnMapping.category ? row[this.columnMapping.category] : '',
                quantity: this.columnMapping.quantity ? row[this.columnMapping.quantity] : undefined,
            })).filter(item => item.name);
        },

        autoMapColumns() {
            const mapping = {};

            this.detectedColumns.forEach(column => {
                const lowerColumn = column.toLowerCase();

                if (lowerColumn.includes('name') || lowerColumn.includes('item')) {
                    mapping.name = column;
                } else if (lowerColumn.includes('category') || lowerColumn.includes('type')) {
                    mapping.category = column;
                } else if (lowerColumn.includes('quantity') || lowerColumn.includes('qty')) {
                    mapping.quantity = column;
                } else if (lowerColumn.includes('unit')) {
                    mapping.unit = column;
                } else if (lowerColumn.includes('description') || lowerColumn.includes('desc')) {
                    mapping.description = column;
                } else if (lowerColumn.includes('location') || lowerColumn.includes('storage')) {
                    mapping.location = column;
                } else if (lowerColumn.includes('price') && lowerColumn.includes('purchase')) {
                    mapping.purchase_price = column;
                } else if (lowerColumn.includes('value') || lowerColumn.includes('price')) {
                    mapping.estimated_value = column;
                }
            });

            this.columnMapping = mapping;
        },

        isValidFileType(file) {
            const validTypes = ['.csv', '.xlsx', '.xls'];
            return validTypes.some(type => file.name.toLowerCase().endsWith(type));
        },

        getFileType(filename) {
            if (filename.endsWith('.csv')) return 'CSV';
            if (filename.endsWith('.xlsx') || filename.endsWith('.xls')) return 'Excel';
            return 'Unknown';
        },

        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },

        formatDateTime(dateString) {
            return new Date(dateString).toLocaleString();
        },

        removeFile() {
            this.uploadedFile = null;
            this.uploadTime = null;
            this.fileAnalysis = null;
            this.detectedColumns = [];
            this.parsedRows = [];
            this.previewData = [];
            this.columnMapping = {};
            this.updateStep1Payload();
        },

        downloadTemplate() {
            const headers = ['Name', 'Category', 'Quantity', 'Unit', 'Description', 'Location', 'Purchase Price', 'Estimated Value'];
            const sampleData = [
                ['Hammer', 'Tools', '1', 'piece', 'Claw hammer for general use', 'Toolbox A', '25.99', '30.00'],
                ['Screws', 'Hardware', '100', 'pack', 'Wood screws 2 inch', 'Storage Bin 3', '12.50', '15.00']
            ];

            const csvContent = [headers, ...sampleData]
                .map(row => row.map(field => `"${field}"`).join(','))
                .join('\n');

            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'inventory_import_template.csv';
            a.click();
            URL.revokeObjectURL(url);
        },

        updateStep1Payload() {
            this.$emit('update', {
                file_name: this.uploadedFile?.name || null,
                upload_time: this.uploadTime,
                file_analysis: this.fileAnalysis,
                detected_columns: this.detectedColumns,
                parsed_rows: this.parsedRows,
                preview_data: this.previewData,
                column_mapping: this.columnMapping,
                items: this.buildItemsFromMapping()
            });
        },

        proceedFromStep1() {
            if (!this.canProceedFromStep1) {
                alert('Please upload a file and map the required Name column before proceeding.');
                return;
            }

            this.updateStep1Payload();
            this.$emit('next');
        },

        // --- Step 6: Import items ---
        async runImport() {
            this.importing = true;
            this.importError = null;
            const created_item_ids = [];
            const errors = [];
            // Each row is created via the same generic POST /api/inventory_items/ endpoint any 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.importResults = {created_item_ids, created_count: created_item_ids.length, errors};
            this.$emit('update', {import_results: this.importResults});
            this.importing = false;
        }
    }
}
</script>

<style scoped>
.upload-dropzone {
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.upload-dropzone:hover,
.upload-dropzone.dragover {
    border-color: #007bff;
    background-color: #f8f9ff;
}

.file-info {
    padding: 1rem;
    background: #f8f9fa;
    border-radius: 8px;
}

.file-analysis {
    background: white;
    padding: 1rem;
    border-radius: 8px;
    margin-top: 1rem;
}
</style>

