<template>
    <div class="foto-first-workflow">
        <!-- Step 1: Photo Capture -->
        <div v-if="step === '1'" class="foto-first-step-1">

            <div class="staging-area mb-4">
                <drag-drop-file-source @input="addStagedFiles">
                    <div class="card">
                        <div class="card-body text-center">
                            <b-icon-upload class="text-primary mb-2" style="font-size: 2.5rem;"></b-icon-upload>
                            <p class="text-muted small mb-3">Drag and drop photos here, or add them below</p>
                            <div class="d-flex justify-content-center gap-2">
                                <fs-file-source @input="addStagedFiles">
                                    <span class="btn btn-outline-success">
                                        <b-icon-upload class="me-1"></b-icon-upload>
                                        Upload Files
                                    </span>
                                </fs-file-source>
                                <camera-file-source @input="addStagedFiles">
                                    <span class="btn btn-outline-primary">
                                        <b-icon-camera class="me-1"></b-icon-camera>
                                        Camera
                                    </span>
                                </camera-file-source>
                                <webcam-file-source @input="addStagedFiles">
                                    <span class="btn btn-outline-primary">
                                        <b-icon-camera-video class="me-1"></b-icon-camera-video>
                                        Webcam
                                    </span>
                                </webcam-file-source>
                            </div>
                        </div>
                    </div>
                </drag-drop-file-source>
            </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">
                            <div class="photo-thumb-wrap">
                                <transition name="photo-wipe">
                                    <img v-if="photo.dataUrl && !photo.uploaded" key="local" :src="photo.dataUrl"
                                         class="card-img-top photo-thumbnail" :alt="`Photo ${index + 1}`">
                                    <authenticated-image v-else key="remote" :src="thumbnailPathForHash(photo.hash)"
                                                          :owner="user" img-class="card-img-top photo-thumbnail"
                                                          :alt="`Photo ${index + 1}`"/>
                                </transition>
                            </div>
                            <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="proceedFromStep1"
                    :disabled="photos.length === 0"
                >
                    Next: Process Images
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>

        <!-- Step 2: Image Processing -->
        <div v-else-if="step === '2'" 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="proceedFromStep2"
                    >
                        Next: Enter Item Details
                        <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                    </button>
                </div>
            </div>
        </div>

        <!-- Step 3: Item Details Entry -->
        <div v-else-if="step === '3'" class="foto-first-step-3">
            <div class="step-header mb-4">
                <h4 class="mb-2">Item Details Entry</h4>
                <p class="text-muted">Enter details for each photographed item to complete the inventory import.</p>
            </div>

            <!-- Progress Indicator -->
            <div class="progress-indicator mb-4">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="mb-0">Item Progress</h6>
                    <span class="badge bg-info">{{ currentItemIndex + 1 }} of {{ totalItems }}</span>
                </div>
                <div class="progress mb-2" style="height: 8px;">
                    <div
                        class="progress-bar bg-info"
                        :style="{ width: itemProgressPercentage + '%' }"
                    ></div>
                </div>
            </div>

            <!-- Current Item Display -->
            <div v-if="currentItem" class="current-item mb-4">
                <div class="row">
                    <!-- Image Preview -->
                    <div class="col-md-4">
                        <div class="card">
                            <img :src="currentItem.processedUrl || currentItem.dataUrl" class="card-img-top item-image"
                                 alt="Current item">
                            <div class="card-body p-2">
                                <small class="text-muted">{{ currentItem.name }}</small>
                            </div>
                        </div>
                    </div>

                    <!-- Item Details Form -->
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h6 class="mb-0">Item Details</h6>
                            </div>
                            <div class="card-body">
                                <form @submit.prevent="saveCurrentItem">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Item Name *</label>
                                            <input
                                                type="text"
                                                class="form-control"
                                                v-model="currentItemDetails.name"
                                                required
                                                placeholder="Enter item name"
                                            >
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Category</label>
                                            <select class="form-select" v-model="currentItemDetails.category">
                                                <option value="">Select category...</option>
                                                <option value="tools">Tools</option>
                                                <option value="electronics">Electronics</option>
                                                <option value="hardware">Hardware</option>
                                                <option value="materials">Materials</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Quantity</label>
                                            <input
                                                type="number"
                                                class="form-control"
                                                v-model.number="currentItemDetails.quantity"
                                                min="1"
                                                placeholder="1"
                                            >
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Unit</label>
                                            <select class="form-select" v-model="currentItemDetails.unit">
                                                <option value="piece">Piece</option>
                                                <option value="set">Set</option>
                                                <option value="box">Box</option>
                                                <option value="pack">Pack</option>
                                                <option value="meter">Meter</option>
                                                <option value="kilogram">Kilogram</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Condition</label>
                                            <select class="form-select" v-model="currentItemDetails.condition">
                                                <option value="new">New</option>
                                                <option value="excellent">Excellent</option>
                                                <option value="good">Good</option>
                                                <option value="fair">Fair</option>
                                                <option value="poor">Poor</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea
                                            class="form-control"
                                            rows="3"
                                            v-model="currentItemDetails.description"
                                            placeholder="Optional description or notes"
                                        ></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Storage Location</label>
                                        <input
                                            type="text"
                                            class="form-control"
                                            v-model="currentItemDetails.location"
                                            placeholder="e.g., Shelf A, Drawer 3, etc."
                                        >
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Purchase Price</label>
                                            <div class="input-group">
                                                <span class="input-group-text">$</span>
                                                <input
                                                    type="number"
                                                    class="form-control"
                                                    v-model.number="currentItemDetails.purchase_price"
                                                    step="0.01"
                                                    min="0"
                                                    placeholder="0.00"
                                                >
                                            </div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Estimated Value</label>
                                            <div class="input-group">
                                                <span class="input-group-text">$</span>
                                                <input
                                                    type="number"
                                                    class="form-control"
                                                    v-model.number="currentItemDetails.estimated_value"
                                                    step="0.01"
                                                    min="0"
                                                    placeholder="0.00"
                                                >
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Item Navigation -->
            <div class="item-navigation mb-4">
                <div class="d-flex justify-content-between align-items-center">
                    <button
                        class="btn btn-outline-secondary"
                        @click="previousItem"
                        :disabled="currentItemIndex === 0"
                    >
                        <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                        Previous Item
                    </button>

                    <div class="btn-group">
                        <button class="btn btn-primary" @click="saveCurrentItem">
                            <b-icon-check class="me-1"></b-icon-check>
                            Save Item
                        </button>
                        <button class="btn btn-outline-primary" @click="skipCurrentItem">
                            <b-icon-skip-forward class="me-1"></b-icon-skip-forward>
                            Skip
                        </button>
                    </div>

                    <button
                        class="btn btn-outline-secondary"
                        @click="nextItem"
                        :disabled="currentItemIndex >= totalItems - 1"
                    >
                        Next Item
                        <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                    </button>
                </div>
            </div>

            <!-- Completed Items Summary -->
            <div v-if="completedItems.length > 0" class="completed-items mb-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">Completed Items ({{ completedItems.length }})</h6>
                        <button class="btn btn-sm btn-outline-info" @click="showCompleted = !showCompleted">
                            <b-icon-eye v-if="!showCompleted"></b-icon-eye>
                            <b-icon-eye-slash v-else></b-icon-eye-slash>
                            {{ showCompleted ? 'Hide' : 'Show' }}
                        </button>
                    </div>
                    <div v-if="showCompleted" class="card-body">
                        <div class="row">
                            <div v-for="(item, index) in completedItems" :key="index"
                                 class="col-sm-6 col-md-4 col-lg-3 mb-2">
                                <div class="d-flex align-items-center">
                                    <img :src="item.image.processedUrl || item.image.dataUrl"
                                         class="completed-item-thumb me-2" alt="Item">
                                    <div class="flex-grow-1">
                                        <div class="fw-bold small">{{ item.details.name }}</div>
                                        <div class="text-muted small">{{ item.details.category || 'No category' }}</div>
                                    </div>
                                    <button class="btn btn-sm btn-outline-secondary" @click="editItem(index)">
                                        <b-icon-pencil></b-icon-pencil>
                                    </button>
                                </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')">
                    <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                    Previous
                </button>
                <button
                    class="btn btn-success"
                    @click="proceedFromStep3"
                    :disabled="completedItems.length === 0"
                >
                    Next: Complete Import ({{ completedItems.length }} items)
                    <b-icon-chevron-right class="ms-1"></b-icon-chevron-right>
                </button>
            </div>
        </div>

        <!-- Step 4: Import Completion -->
        <div v-else-if="step === '4'" class="foto-first-step-4">
            <div class="step-header mb-4">
                <h4 class="mb-2">Import Completion</h4>
                <p class="text-muted">Review and finalize your imported items.</p>
            </div>

            <!-- Import Summary -->
            <div class="import-summary mb-4">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-primary mb-2">{{ finalTotalItems }}</h3>
                                <p class="card-text text-muted mb-0">Items Imported</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-success mb-2">{{ categorizedItems }}</h3>
                                <p class="card-text text-muted mb-0">With Categories</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-info mb-2">{{ itemsWithLocation }}</h3>
                                <p class="card-text text-muted mb-0">With Locations</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <h3 class="text-warning mb-2">${{ totalValue }}</h3>
                                <p class="card-text text-muted mb-0">Total Value</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Category Breakdown -->
            <div class="category-breakdown mb-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Items by Category</h6>
                    </div>
                    <div class="card-body">
                        <div v-if="Object.keys(categoryBreakdown).length > 0" class="row">
                            <div v-for="(count, category) in categoryBreakdown" :key="category"
                                 class="col-sm-6 col-md-4 col-lg-3 mb-2">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="text-capitalize">{{ category || 'Uncategorized' }}</span>
                                    <span class="badge bg-secondary">{{ count }}</span>
                                </div>
                            </div>
                        </div>
                        <div v-else class="text-muted text-center py-3">
                            No items to categorize
                        </div>
                    </div>
                </div>
            </div>

            <!-- Import Options -->
            <div class="import-options mb-4">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Import Options</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        id="generateQr"
                                        v-model="importOptions.generate_qr_codes"
                                    >
                                    <label class="form-check-label" for="generateQr">
                                        Generate QR codes for items
                                    </label>
                                </div>
                                <div class="form-check mb-3">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        id="sendNotification"
                                        v-model="importOptions.send_notification"
                                    >
                                    <label class="form-check-label" for="sendNotification">
                                        Send completion notification
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check mb-3">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        id="createReport"
                                        v-model="importOptions.create_report"
                                    >
                                    <label class="form-check-label" for="createReport">
                                        Create import report
                                    </label>
                                </div>
                                <div class="form-check mb-3">
                                    <input
                                        class="form-check-input"
                                        type="checkbox"
                                        id="autoBackup"
                                        v-model="importOptions.auto_backup"
                                    >
                                    <label class="form-check-label" for="autoBackup">
                                        Auto-backup imported data
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Item List -->
            <div class="item-list mb-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">Imported Items</h6>
                        <div class="btn-group btn-group-sm">
                            <button
                                class="btn"
                                :class="viewMode === 'grid' ? 'btn-primary' : 'btn-outline-primary'"
                                @click="viewMode = 'grid'"
                            >
                                <b-icon-grid></b-icon-grid>
                            </button>
                            <button
                                class="btn"
                                :class="viewMode === 'list' ? 'btn-primary' : 'btn-outline-primary'"
                                @click="viewMode = 'list'"
                            >
                                <b-icon-list></b-icon-list>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- Grid View -->
                        <div v-if="viewMode === 'grid'" class="row">
                            <div v-for="(item, index) in completedItems" :key="index"
                                 class="col-sm-6 col-md-4 col-lg-3 mb-3">
                                <div class="card h-100">
                                    <img :src="item.image.processedUrl || item.image.dataUrl"
                                         class="card-img-top item-thumb" :alt="item.details.name">
                                    <div class="card-body p-2">
                                        <h6 class="card-title mb-1">{{ item.details.name }}</h6>
                                        <p class="card-text small text-muted mb-1">
                                            {{ item.details.category || 'No category' }}</p>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted">Qty: {{ item.details.quantity }}</small>
                                            <small v-if="item.details.estimated_value"
                                                   class="text-success">${{ item.details.estimated_value }}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- List View -->
                        <div v-else class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                <tr>
                                    <th>Image</th>
                                    <th>Name</th>
                                    <th>Category</th>
                                    <th>Quantity</th>
                                    <th>Location</th>
                                    <th>Value</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr v-for="(item, index) in completedItems" :key="index">
                                    <td>
                                        <img :src="item.image.processedUrl || item.image.dataUrl"
                                             class="list-item-thumb" :alt="item.details.name">
                                    </td>
                                    <td class="fw-bold">{{ item.details.name }}</td>
                                    <td>
                                        <span v-if="item.details.category"
                                              class="badge bg-light text-dark">{{ item.details.category }}</span>
                                        <span v-else class="text-muted">-</span>
                                    </td>
                                    <td>{{ item.details.quantity }} {{ item.details.unit }}</td>
                                    <td>{{ item.details.location || '-' }}</td>
                                    <td>
                                        <span v-if="item.details.estimated_value"
                                              class="text-success">${{ item.details.estimated_value }}</span>
                                        <span v-else class="text-muted">-</span>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Final Action -->
            <div class="final-action text-center">
                <div class="card">
                    <div class="card-body py-4">
                        <b-icon-check-circle class="text-success mb-3" style="font-size: 3rem;"></b-icon-check-circle>
                        <h5 class="mb-3">Ready to Complete Import</h5>
                        <p class="text-muted mb-4">
                            All {{ finalTotalItems }} items have been processed and are ready to be added to your
                            inventory.
                            This action cannot be undone.
                        </p>
                        <div class="d-flex justify-content-center gap-3">
                            <button class="btn btn-outline-secondary" @click="$emit('prev')">
                                <b-icon-chevron-left class="me-1"></b-icon-chevron-left>
                                Go Back
                            </button>
                            <button
                                class="btn btn-success btn-lg"
                                @click="completeImport"
                                :disabled="importing"
                            >
                                <div v-if="importing" class="spinner-border spinner-border-sm me-2" role="status"></div>
                                <b-icon-check-circle v-else class="me-2"></b-icon-check-circle>
                                {{ importing ? 'Importing...' : 'Complete Import' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Fallback for unknown steps -->
        <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">Unknown step "{{ step }}"</h5>
        </div>
    </div>
</template>

<script>
import * as BIcons from "bootstrap-icons-vue";
import {mapActions, mapState} from "vuex";
import AuthenticatedImage from "@/components/AuthenticatedImage.vue";
import DragDropFileSource from "@/components/inputs/DragDropFileSource.vue";
import CameraFileSource from "@/components/inputs/CameraFileSource.vue";
import FsFileSource from "@/components/inputs/FsFileSource.vue";
import WebcamFileSource from "@/components/inputs/WebcamFileSource.vue";

export default {
    name: 'FotoFirstBulkImportWorkflow',
    meta: {
        slug: 'foto-first-bulk-import',
        title: 'Foto First Bulk Import',
        category: 'Data Management',
        description: 'Capture unlimited photos via mobile camera or upload images, then sequentially enter details for each item.',
        icons: ['b-icon-camera', 'b-icon-pencil-square'],
        estimatedDuration: '10-60 minutes',
        stepDefinitions: [
            {step: '1', name: 'Photo Capture', description: 'Capture or upload item photos'},
            {step: '2', name: 'Image Processing', description: 'Process and optimize images'},
            {step: '3', name: 'Item Details Entry', description: 'Enter details for each photographed item'},
            {step: '4', name: 'Import Completion', description: 'Finalize and save imported items'}
        ],
        getInitialPayload() {
            return {
                processing_options: {
                    auto_rotate: true,
                    compress: true,
                    max_width: 1920,
                    max_height: 1080
                }
            };
        }
    },
    components: {
        WebcamFileSource,
        AuthenticatedImage,
        DragDropFileSource,
        CameraFileSource,
        FsFileSource,
        ...BIcons
    },
    props: {
        workflowInstance: {
            type: Object,
            required: true
        },
        step: {
            type: String,
            required: true
        },
        payload: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            // Step 1: photo capture
            photos: [],

            // Step 2: image processing
            processing: false,
            processedCount: 0,
            currentlyProcessing: null,
            processedImages: [],
            processingOptions: {
                auto_rotate: true,
                compress: true,
                max_width: 1920,
                max_height: 1080
            },

            // Step 3: item details entry
            currentItemIndex: 0,
            currentItemDetails: this.getDefaultItemDetails(),
            completedItems: [],
            showCompleted: false,

            // Step 4: completion
            importing: false,
            viewMode: 'grid',
            importOptions: {
                generate_qr_codes: true,
                send_notification: true,
                create_report: true,
                auto_backup: false
            }
        }
    },
    computed: {
        ...mapState(['user']),
        // Step 1/2
        totalPhotos() {
            return this.photos.length;
        },
        progressPercentage() {
            return this.totalPhotos > 0 ? (this.processedCount / this.totalPhotos) * 100 : 0;
        },
        isComplete() {
            return this.processedCount === this.totalPhotos && this.totalPhotos > 0;
        },

        // Step 3
        availableItems() {
            return this.processedImages.length > 0 ? this.processedImages : this.photos;
        },
        totalItems() {
            return this.availableItems.length;
        },
        currentItem() {
            return this.availableItems[this.currentItemIndex] || null;
        },
        itemProgressPercentage() {
            return this.totalItems > 0 ? (this.completedItems.length / this.totalItems) * 100 : 0;
        },

        // Step 4
        finalTotalItems() {
            return this.completedItems.length;
        },
        categorizedItems() {
            return this.completedItems.filter(item => item.details.category).length;
        },
        itemsWithLocation() {
            return this.completedItems.filter(item => item.details.location).length;
        },
        totalValue() {
            return this.completedItems.reduce((sum, item) => {
                return sum + (item.details.estimated_value || 0);
            }, 0).toFixed(2);
        },
        categoryBreakdown() {
            const breakdown = {};
            this.completedItems.forEach(item => {
                const category = item.details.category || 'uncategorized';
                breakdown[category] = (breakdown[category] || 0) + 1;
            });
            return breakdown;
        }
    },
    mounted() {
        this.loadFromPayload();
    },
    beforeUnmount() {
        this.processedImages.forEach(image => {
            if (image.processedUrl && image.processedUrl.startsWith('blob:')) {
                URL.revokeObjectURL(image.processedUrl);
            }
        });
    },
    methods: {
        ...mapActions(['stageFile', 'unstageFile']),
        loadFromPayload() {
            // `photos` is seeded from workflowInstance.staged_files, not payload. See docs/implementation.md#staged-photos-are-the-durable-state.
            this.photos = (this.workflowInstance.staged_files || []).map(hash => ({
                hash,
                name: null,
                size: null,
                mime_type: null,
                dataUrl: null,
                uploaded: true,
                timestamp: null
            }));
            if (this.payload.processing_options) {
                this.processingOptions = {...this.processingOptions, ...this.payload.processing_options};
            }
            if (this.payload.processed_images) {
                this.processedImages = [...this.payload.processed_images];
                this.processedCount = this.processedImages.length;
            }
            if (this.payload.completed_items) this.completedItems = [...this.payload.completed_items];
            if (this.payload.current_item_details) this.currentItemDetails = {...this.payload.current_item_details};
            if (this.payload.current_item_index !== undefined) this.currentItemIndex = this.payload.current_item_index;
            if (this.payload.import_options) this.importOptions = {...this.importOptions, ...this.payload.import_options};
        },

        // --- Step 1: Photo capture ---
        thumbnailPathForHash(hash, size = 256) {
            // Derived storage path for a disk-cached resized thumbnail. See docs/implementation.md#thumbnail-lookup-by-hash.
            return `/media/${size}/${hash.slice(0, 2)}/${hash.slice(2, 4)}/${hash.slice(4, 6)}/${hash.slice(6)}/`;
        },

        async addStagedFiles(files) {
            const new_files = files.filter(file => !this.photos.find(photo => photo.hash === file.hash));
            if (new_files.length === 0) return;

            const staged = new_files.map(file => ({
                name: file.name,
                size: file.size,
                mime_type: file.mime_type,
                hash: file.hash, // SHA-256, same algorithm the backend hashes File content with
                data: file.data,
                dataUrl: `data:${file.mime_type};base64,${file.data}`,
                uploaded: false,
                timestamp: new Date().toISOString()
            }));
            this.photos.push(...staged);

            // Persists each photo server-side immediately so it survives a reload/device switch. See docs/implementation.md#staged-photos-are-the-durable-state.
            await Promise.all(staged.map(async ({hash, data, mime_type}) => {
                try {
                    await this.stageFile({
                        lifetime_id: this.workflowInstance.id,
                        file: {data, mime_type}
                    });
                    // Re-lookup by hash rather than mutate the closed-over `photo`, which predates this.photos.push() and isn't Vue's reactive proxy. See docs/implementation.md#thumbnail-lookup-by-hash.
                    const photo = this.photos.find(p => p.hash === hash);
                    if (photo) photo.uploaded = true;
                } catch (error) {
                    console.error('Failed to stage photo:', error);
                    this.photos = this.photos.filter(p => p.hash !== hash);
                }
            }));
        },

        async removePhoto(index) {
            const [photo] = this.photos.splice(index, 1);
            if (photo) {
                try {
                    await this.unstageFile({lifetime_id: this.workflowInstance.id, file_hash: photo.hash});
                } catch (error) {
                    console.error('Failed to unstage photo:', error);
                }
            }
        },

        async clearAllPhotos() {
            if (confirm('Are you sure you want to remove all photos?')) {
                const removed = this.photos;
                this.photos = [];
                await Promise.all(removed.map(photo =>
                    this.unstageFile({lifetime_id: this.workflowInstance.id, file_hash: photo.hash})
                        .catch(error => console.error('Failed to unstage photo:', error))
                ));
            }
        },

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

        // --- Step 2: Image processing ---
        async startProcessing() {
            if (this.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.photos.length; i++) {
                    const photo = this.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.updateProcessingPayload();
            } 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.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.dataUrl;
            });
        },

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

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

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

        proceedFromStep2() {
            this.updateProcessingPayload();
            this.$emit('next');
        },

        // --- Step 3: Item details entry ---
        getDefaultItemDetails() {
            return {
                name: '',
                category: '',
                quantity: 1,
                unit: 'piece',
                condition: 'good',
                description: '',
                location: '',
                purchase_price: null,
                estimated_value: null
            };
        },

        saveCurrentItem() {
            if (!this.currentItemDetails.name.trim()) {
                alert('Please enter an item name before saving.');
                return;
            }

            const itemData = {
                image: this.currentItem,
                details: {...this.currentItemDetails},
                saved_at: new Date().toISOString()
            };

            const existingIndex = this.completedItems.findIndex(item =>
                item.image === this.currentItem
            );

            if (existingIndex >= 0) {
                this.completedItems.splice(existingIndex, 1, itemData);
            } else {
                this.completedItems.push(itemData);
            }

            this.nextItem();
            this.updateItemsPayload();
        },

        skipCurrentItem() {
            this.nextItem();
        },

        nextItem() {
            if (this.currentItemIndex < this.totalItems - 1) {
                this.currentItemIndex++;
                this.currentItemDetails = this.getDefaultItemDetails();
            }
        },

        previousItem() {
            if (this.currentItemIndex > 0) {
                this.currentItemIndex--;

                const existingItem = this.completedItems.find(item =>
                    item.image === this.currentItem
                );

                if (existingItem) {
                    this.currentItemDetails = {...existingItem.details};
                } else {
                    this.currentItemDetails = this.getDefaultItemDetails();
                }
            }
        },

        editItem(index) {
            const item = this.completedItems[index];
            const itemIndex = this.availableItems.findIndex(img => img === item.image);
            if (itemIndex >= 0) {
                this.currentItemIndex = itemIndex;
                this.currentItemDetails = {...item.details};
            }
        },

        updateItemsPayload() {
            this.$emit('update', {
                completed_items: this.completedItems,
                current_item_details: this.currentItemDetails,
                current_item_index: this.currentItemIndex
            });
        },

        proceedFromStep3() {
            if (this.completedItems.length === 0) {
                alert('Please complete at least one item before proceeding.');
                return;
            }

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

        // --- Step 4: Completion ---
        async completeImport() {
            if (this.finalTotalItems === 0) {
                alert('No items to import. Please go back and add items.');
                return;
            }

            const confirmed = confirm(
                `Are you sure you want to import ${this.finalTotalItems} items? This action cannot be undone.`
            );

            if (!confirmed) return;

            try {
                this.importing = true;

                this.updateFinalPayload();

                // Simulate import process
                await new Promise(resolve => setTimeout(resolve, 2000));

                this.$emit('update', {
                    import_completed: true,
                    completion_timestamp: new Date().toISOString()
                });

                this.$emit('complete');
            } catch (error) {
                console.error('Error completing import:', error);
                alert('Error completing import. Please try again.');
            } finally {
                this.importing = false;
            }
        },

        updateFinalPayload() {
            this.$emit('update', {
                import_options: this.importOptions,
                final_summary: {
                    total_items: this.finalTotalItems,
                    categorized_items: this.categorizedItems,
                    items_with_location: this.itemsWithLocation,
                    total_value: parseFloat(this.totalValue),
                    category_breakdown: this.categoryBreakdown
                }
            });
        }
    }
}
</script>

<style scoped>
.photo-thumbnail,
.item-thumb {
    height: 150px;
    object-fit: cover;
}

/* Stacks the dataUrl preview and server-fetched image during their crossfade so neither disappears before the other lays out. */
.photo-thumb-wrap {
    position: relative;
    height: 150px;
    overflow: hidden;
}

.photo-thumb-wrap .photo-thumbnail {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.photo-wipe-enter-active,
.photo-wipe-leave-active {
    transition: clip-path 0.5s ease, opacity 0.5s ease;
}

.photo-wipe-enter-from {
    clip-path: inset(0 100% 0 0);
    opacity: 0.6;
}

.photo-wipe-enter-to {
    clip-path: inset(0 0 0 0);
    opacity: 1;
}

.photo-wipe-leave-from {
    opacity: 1;
}

.photo-wipe-leave-to {
    opacity: 0;
}

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

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

.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;
    }
}

.item-image {
    height: 300px;
    object-fit: cover;
}

.completed-item-thumb {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

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

.list-item-thumb {
    width: 40px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

.final-action .card {
    border: 2px solid #28a745;
    background: linear-gradient(135deg, #f8fff8 0%, #e8f5e8 100%);
}
</style>