<template>
    <div class="foto-first-step-2">
        <div class="step-header mb-4">
            <h4 class="mb-2">Image Processing</h4>
            <p class="text-muted">Processing and optimizing your captured images...</p>
        </div>

        <!-- Processing Status -->
        <div class="processing-status mb-4">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0">Processing Progress</h6>
                        <span class="badge bg-primary">{{ processedCount }}/{{ totalPhotos }}</span>
                    </div>

                    <div class="progress mb-3" style="height: 12px;">
                        <div
                            class="progress-bar progress-bar-striped progress-bar-animated"
                            :style="{ width: progressPercentage + '%' }"
                            :class="{ 'bg-success': isComplete, 'bg-primary': !isComplete }"
                        ></div>
                    </div>

                    <div class="processing-details">
                        <div v-if="currentlyProcessing" class="d-flex align-items-center text-muted">
                            <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                            <span>Processing: {{ currentlyProcessing }}</span>
                        </div>
                        <div v-else-if="isComplete" class="d-flex align-items-center text-success">
                            <b-icon-check-circle class="me-2"></b-icon-check-circle>
                            <span>All images processed successfully!</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Processing Options -->
        <div class="processing-options mb-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Processing Options</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check mb-2">
                                <input
                                    class="form-check-input"
                                    type="checkbox"
                                    id="autoRotate"
                                    v-model="processingOptions.auto_rotate"
                                    :disabled="processing"
                                >
                                <label class="form-check-label" for="autoRotate">
                                    Auto-rotate images based on EXIF data
                                </label>
                            </div>
                            <div class="form-check mb-2">
                                <input
                                    class="form-check-input"
                                    type="checkbox"
                                    id="compress"
                                    v-model="processingOptions.compress"
                                    :disabled="processing"
                                >
                                <label class="form-check-label" for="compress">
                                    Compress images for optimal storage
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Max Width (px)</label>
                                <input
                                    type="number"
                                    class="form-control"
                                    v-model.number="processingOptions.max_width"
                                    :disabled="processing"
                                    min="480"
                                    max="4096"
                                >
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Max Height (px)</label>
                                <input
                                    type="number"
                                    class="form-control"
                                    v-model.number="processingOptions.max_height"
                                    :disabled="processing"
                                    min="480"
                                    max="4096"
                                >
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Processed Images Preview -->
        <div v-if="processedImages.length > 0" class="processed-images mb-4">
            <h6 class="mb-3">Processed Images</h6>
            <div class="row">
                <div v-for="(image, index) in processedImages" :key="index" class="col-sm-6 col-md-4 col-lg-3 mb-3">
                    <div class="card">
                        <img :src="image.processedUrl" class="card-img-top processed-thumbnail" :alt="`Processed ${index + 1}`">
                        <div class="card-body p-2">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <small class="text-muted">{{ image.name }}</small>
                                <span class="badge bg-success">
                                    <b-icon-check></b-icon-check>
                                </span>
                            </div>
                            <div class="processing-info">
                                <small class="text-muted d-block">
                                    {{ formatFileSize(image.originalSize) }} → {{ formatFileSize(image.processedSize) }}
                                </small>
                                <small class="text-success">
                                    {{ Math.round(((image.originalSize - image.processedSize) / image.originalSize) * 100) }}% reduced
                                </small>
                            </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')" :disabled="processing">
                <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                Previous
            </button>
            <div class="d-flex gap-2">
                <button
                    v-if="!processing && !isComplete"
                    class="btn btn-primary"
                    @click="startProcessing"
                >
                    <b-icon-gear class="me-1"></b-icon-gear>
                    Start Processing
                </button>
                <button
                    v-if="isComplete"
                    class="btn btn-success"
                    @click="proceedToNext"
                >
                    Next: Enter Item Details
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: 'FotoFirstStep2',
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            processing: false,
            processedCount: 0,
            currentlyProcessing: null,
            processedImages: [],
            processingOptions: {
                auto_rotate: true,
                compress: true,
                max_width: 1920,
                max_height: 1080
            }
        }
    },
    computed: {
        totalPhotos() {
            return this.payload.photos?.length || 0;
        },
        progressPercentage() {
            return this.totalPhotos > 0 ? (this.processedCount / this.totalPhotos) * 100 : 0;
        },
        isComplete() {
            return this.processedCount === this.totalPhotos && this.totalPhotos > 0;
        }
    },
    mounted() {
        // Load processing options from payload
        if (this.payload.processing_options) {
            this.processingOptions = { ...this.processingOptions, ...this.payload.processing_options };
        }

        // Load processed images if they exist
        if (this.payload.processed_images) {
            this.processedImages = [...this.payload.processed_images];
            this.processedCount = this.processedImages.length;
        }
    },
    methods: {
        async startProcessing() {
            if (!this.payload.photos || this.payload.photos.length === 0) {
                alert('No photos to process. Please go back and add photos first.');
                return;
            }

            this.processing = true;
            this.processedCount = 0;
            this.processedImages = [];

            try {
                for (let i = 0; i < this.payload.photos.length; i++) {
                    const photo = this.payload.photos[i];
                    this.currentlyProcessing = photo.name;

                    const processedImage = await this.processImage(photo);
                    this.processedImages.push(processedImage);
                    this.processedCount++;

                    // Small delay to show progress
                    await new Promise(resolve => setTimeout(resolve, 500));
                }

                this.currentlyProcessing = null;
                this.updatePayload();
            } catch (error) {
                console.error('Error processing images:', error);
                alert('Error processing images. Please try again.');
            } finally {
                this.processing = false;
            }
        },

        async processImage(photo) {
            return new Promise((resolve) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');

                    // Calculate new dimensions
                    let { width, height } = this.calculateDimensions(
                        img.width,
                        img.height,
                        this.processingOptions.max_width,
                        this.processingOptions.max_height
                    );

                    canvas.width = width;
                    canvas.height = height;

                    // Draw and compress
                    ctx.drawImage(img, 0, 0, width, height);

                    canvas.toBlob(blob => {
                        const processedImage = {
                            name: photo.name,
                            originalSize: photo.file.size,
                            processedSize: blob.size,
                            processedUrl: URL.createObjectURL(blob),
                            processedFile: blob,
                            timestamp: new Date().toISOString()
                        };
                        resolve(processedImage);
                    }, 'image/jpeg', this.processingOptions.compress ? 0.8 : 0.95);
                };
                img.src = photo.preview;
            });
        },

        calculateDimensions(originalWidth, originalHeight, maxWidth, maxHeight) {
            let width = originalWidth;
            let height = originalHeight;

            // Scale down if needed
            if (width > maxWidth) {
                height = (height * maxWidth) / width;
                width = maxWidth;
            }

            if (height > maxHeight) {
                width = (width * maxHeight) / height;
                height = maxHeight;
            }

            return { width: Math.round(width), height: Math.round(height) };
        },

        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];
        },

        updatePayload() {
            this.$emit('update', {
                processing_options: this.processingOptions,
                processed_images: this.processedImages
            });
        },

        proceedToNext() {
            this.updatePayload();
            this.$emit('next');
        }
    },

    beforeDestroy() {
        // Clean up object URLs
        this.processedImages.forEach(image => {
            if (image.processedUrl && image.processedUrl.startsWith('blob:')) {
                URL.revokeObjectURL(image.processedUrl);
            }
        });
    }
}
</script>

<style scoped>
.processed-thumbnail {
    height: 120px;
    object-fit: cover;
}

.processing-info {
    font-size: 0.75rem;
}

.progress-bar-animated {
    animation: progress-bar-stripes 1s linear infinite;
}

@keyframes progress-bar-stripes {
    0% {
        background-position: 1rem 0;
    }
    100% {
        background-position: 0 0;
    }
}
</style>
