<template>
    <div class="foto-first-step-1">
        <div class="step-header mb-4">
            <h4 class="mb-2">Photo Capture</h4>
            <p class="text-muted">Capture or upload item photos to begin the import process.</p>
        </div>

        <div class="upload-area mb-4">
            <div class="row">
                <!-- Camera Capture -->
                <div class="col-md-6 mb-3">
                    <div class="card h-100">
                        <div class="card-body text-center">
                            <b-icon-camera class="text-primary mb-3" style="font-size: 3rem;"></b-icon-camera>
                            <h6>Camera Capture</h6>
                            <p class="text-muted small">Use your device camera to capture photos</p>
                            <button class="btn btn-primary" @click="startCamera" :disabled="loading">
                                <b-icon-camera class="me-1"></b-icon-camera>
                                Start Camera
                            </button>
                        </div>
                    </div>
                </div>

                <!-- File Upload -->
                <div class="col-md-6 mb-3">
                    <div class="card h-100">
                        <div class="card-body text-center">
                            <b-icon-upload class="text-success mb-3" style="font-size: 3rem;"></b-icon-upload>
                            <h6>File Upload</h6>
                            <p class="text-muted small">Upload photos from your device</p>
                            <input
                                type="file"
                                ref="fileInput"
                                multiple
                                accept="image/*"
                                @change="handleFileUpload"
                                class="d-none"
                            />
                            <button class="btn btn-success" @click="$refs.fileInput.click()" :disabled="loading">
                                <b-icon-upload class="me-1"></b-icon-upload>
                                Upload Photos
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Camera Preview -->
        <div v-if="showCamera" class="camera-section mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Camera Preview</h6>
                    <button class="btn btn-sm btn-outline-secondary" @click="stopCamera">
                        <b-icon-x></b-icon-x>
                    </button>
                </div>
                <div class="card-body">
                    <div class="camera-container text-center">
                        <video ref="video" autoplay muted class="camera-preview mb-3"></video>
                        <div>
                            <button class="btn btn-primary me-2" @click="capturePhoto" :disabled="!cameraReady">
                                <b-icon-camera class="me-1"></b-icon-camera>
                                Capture Photo
                            </button>
                            <button class="btn btn-outline-secondary" @click="stopCamera">
                                <b-icon-stop class="me-1"></b-icon-stop>
                                Stop Camera
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Photo Gallery -->
        <div v-if="photos.length > 0" class="photo-gallery mb-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0">Captured Photos ({{ photos.length }})</h6>
                <button class="btn btn-sm btn-outline-danger" @click="clearAllPhotos">
                    <b-icon-trash class="me-1"></b-icon-trash>
                    Clear All
                </button>
            </div>
            <div class="row">
                <div v-for="(photo, index) in photos" :key="index" class="col-sm-6 col-md-4 col-lg-3 mb-3">
                    <div class="card">
                        <img :src="photo.preview" class="card-img-top photo-thumbnail" :alt="`Photo ${index + 1}`">
                        <div class="card-body p-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">Photo {{ index + 1 }}</small>
                                <button class="btn btn-sm btn-outline-danger" @click="removePhoto(index)">
                                    <b-icon-trash></b-icon-trash>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navigation -->
        <div class="step-navigation d-flex justify-content-between">
            <div></div>
            <button
                class="btn btn-primary"
                @click="proceedToNext"
                :disabled="photos.length === 0 || loading"
            >
                Next: Process Images
                <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: 'FotoFirstStep1',
    components: {
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            loading: false,
            showCamera: false,
            cameraReady: false,
            photos: [],
            stream: null
        }
    },
    mounted() {
        // Load existing photos from payload
        if (this.payload.photos) {
            this.photos = [...this.payload.photos];
        }
    },
    beforeDestroy() {
        this.stopCamera();
    },
    methods: {
        async startCamera() {
            try {
                this.loading = true;
                this.stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: 'environment' }
                });
                this.$refs.video.srcObject = this.stream;
                this.showCamera = true;
                this.cameraReady = true;
            } catch (error) {
                console.error('Error accessing camera:', error);
                alert('Could not access camera. Please check permissions or use file upload instead.');
            } finally {
                this.loading = false;
            }
        },

        stopCamera() {
            if (this.stream) {
                this.stream.getTracks().forEach(track => track.stop());
                this.stream = null;
            }
            this.showCamera = false;
            this.cameraReady = false;
        },

        capturePhoto() {
            if (!this.cameraReady) return;

            const canvas = document.createElement('canvas');
            const video = this.$refs.video;
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0);

            canvas.toBlob(blob => {
                const photo = {
                    file: blob,
                    preview: URL.createObjectURL(blob),
                    name: `camera-photo-${Date.now()}.jpg`,
                    timestamp: new Date().toISOString()
                };
                this.photos.push(photo);
                this.updatePayload();
            }, 'image/jpeg', 0.8);
        },

        handleFileUpload(event) {
            const files = Array.from(event.target.files);
            files.forEach(file => {
                if (file.type.startsWith('image/')) {
                    const photo = {
                        file: file,
                        preview: URL.createObjectURL(file),
                        name: file.name,
                        timestamp: new Date().toISOString()
                    };
                    this.photos.push(photo);
                }
            });
            this.updatePayload();
            event.target.value = '';
        },

        removePhoto(index) {
            URL.revokeObjectURL(this.photos[index].preview);
            this.photos.splice(index, 1);
            this.updatePayload();
        },

        clearAllPhotos() {
            if (confirm('Are you sure you want to remove all photos?')) {
                this.photos.forEach(photo => URL.revokeObjectURL(photo.preview));
                this.photos = [];
                this.updatePayload();
            }
        },

        updatePayload() {
            this.$emit('update', { photos: this.photos });
        },

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

<style scoped>
.camera-preview {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
}

.photo-thumbnail {
    height: 150px;
    object-fit: cover;
}

.upload-area .card {
    transition: transform 0.2s ease-in-out;
}

.upload-area .card:hover {
    transform: translateY(-2px);
}

.camera-container {
    position: relative;
}
</style>
