<template>
    <div 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="processing" 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 && !processing" 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="proceedToNext"
                :disabled="!canProceed"
            >
                Next: Parse Data
                <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: 'BulkImportStep1',
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            uploadedFile: null,
            uploadTime: null,
            processing: 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 }
            ]
        }
    },
    computed: {
        canProceed() {
            return this.uploadedFile && this.fileAnalysis && this.columnMapping.name;
        }
    },
    mounted() {
        // 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: {
        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.processing = true;
            this.processingStatus = 'Reading file...';

            try {
                // Simulate file processing
                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.updatePayload();
            } catch (error) {
                console.error('Error processing file:', error);
                alert('Error processing file. Please try again.');
                this.removeFile();
            } finally {
                this.processing = false;
                this.processingStatus = '';
            }
        },

        async analyzeFile(file) {
            // Parsing happens entirely client-side. The backend never sees the
            // raw file - only the structured `items` list produced here, sent
            // later as generic payload/request body.
            if (file.name.endsWith('.csv')) {
                const text = await file.text();
                this.parsedRows = this.parseCsv(text);
            } else {
                // For Excel files, you'd use a library like SheetJS to parse
                // client-side. This is a mock implementation.
                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
            };

            // Auto-map columns based on common names
            this.autoMapColumns();
        },

        // Simple CSV parser: no external dependency, entirely client-side.
        // Returns an array of row objects keyed by the detected header columns.
        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;
            });
        },

        // Convert the fully parsed rows + column mapping into the generic item
        // dicts consumed by the "Import Items" step, which creates each one via
        // the standard generic InventoryItem create endpoint.
        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.updatePayload();
        },

        downloadTemplate() {
            // Create a sample CSV template
            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);
        },

        updatePayload() {
            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()
            });
        },

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

            this.updatePayload();
            this.$emit('next');
        }
    }
}
</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>
