<template>
    <div>
        <h1>Folder: {{ folder }}</h1>
        <div class="selection-controls">
            <button @click="selectAll">Select All</button>
            <button @click="selectNone">Select None</button>
            <button @click="selectInverse">Inverse Selection</button>
            <button @click="deleteSelected" class="delete-button">Delete Selected</button>
            <button 
                @click="toggleSelectionMode" 
                :class="{ active: selectionMode }" 
                class="mode-button">
                {{ selectionMode ? 'Selection Mode: ON' : 'Selection Mode: OFF' }}
            </button>
            <button @click="analyzeImages()">Analyze All</button>
            <input v-model="targetFolder" placeholder="Target folder name">
            <button @click="copyToFolder">Copy to Folder</button>
            <div class="size-control">
                <label for="imageSize">Image Size: {{ imageSize }}px</label>
                <input 
                    type="range" 
                    id="imageSize" 
                    v-model="imageSize" 
                    min="100" 
                    max="1000" 
                    step="10">
            </div>
            <div class="pagination-controls">
                <span>Total: {{ total }}</span>
                <button 
                    :disabled="start === 0" 
                    @click="previousPage">Previous</button>
                <span>Page {{ currentPage }} of {{ totalPages }}</span>
                <button 
                    :disabled="start + pageSize >= total" 
                    @click="nextPage">Next</button>
                <select v-model="pageSize">
                    <option :value="20">20 per page</option>
                    <option :value="50">50 per page</option>
                    <option :value="100">100 per page</option>
                </select>
            </div>
        </div>
        <div class="datapoints">
            <div class="datapoint" v-for="dp in datapoints" :key="dp.path">
                <div class="datapoint-container">
                    <input type="checkbox" v-model="selectedDatapoints[dp.path]">
                    <router-link 
                        target="_blank" 
                        :to="selectionMode ? null : `/datapoint/${folder}/${dp.basename}`" 
                        @click.prevent="handleImageClick(dp)">
                        <img :title="datapoint_title(dp)" class="datapoint-image" :src="dp.image_data_url">
                        <img v-if="dp.dot_area" class="datapoint-dot-area" :src="dp.dot_area">
                        <div v-if="dp.analyze_result" class="analyze-result">
                            {{ dp.analyze_result }}
                        </div>
                        <span class="datapoint-datetime">{{ dp.datetime }}</span>
                    </router-link>
                </div>
            </div>
        </div>
        
        <!-- Add modal component -->
        <div v-if="selectedImage" class="modal" @click="closeModal">
            <img :src="selectedImage.image_data_url" class="modal-image">
            <div class="analyze-result" v-if="selectedImage.analyze_result"> {{ selectedImage.analyze_result }}</div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'FolderView',
    props: ['folder'],
    data() {
        return {
            datapoints: [],
            selectedDatapoints: {},
            selectedDatapointPaths: [],
            targetFolder: '',
            imageSize: parseInt(localStorage.getItem('imageSize')) || 200,
            selectedImage: null,
            selectionMode: false,
            isAnalyzing: false,
            showDropdown: false,
            total: 0,
            start: 0,
            pageSize: 20,
        }
    },
    computed: {
        currentPage() {
            return Math.floor(this.start / this.pageSize) + 1;
        },
        totalPages() {
            return Math.ceil(this.total / this.pageSize);
        }
    },
    watch: {
        imageSize(newSize) {
            localStorage.setItem('imageSize', newSize);
        },
        pageSize() {
            this.start = 0; // Reset to first page when changing page size
            this.reload();
        }
    },
    mounted() {
        this.reload();
    },
    methods: {
        async reload() {
            this.datapoints = [];
            const res = await fetch(`/api/datapoints?folder=${this.folder}&start=${this.start}&count=${this.pageSize}`);
            const data = await res.json();
            this.datapoints = data.datapoints.sort((a, b) => a.session_id - b.session_id);
            this.total = data.total;
            
            // Initialize selection state for new datapoints
            this.selectedDatapoints = {};
            for (const datapoint of this.datapoints) {
                this.selectedDatapoints[datapoint.path] = false;
            }
        },
        selectAll() {
            for (const datapoint of this.datapoints) {
                this.selectedDatapoints[datapoint.path] = true;
            }
        },
        selectNone() {
            for (const datapoint of this.datapoints) {
                this.selectedDatapoints[datapoint.path] = false;
            }
        },
        selectInverse() {
            for (const datapoint of this.datapoints) {
                this.selectedDatapoints[datapoint.path] = !this.selectedDatapoints[datapoint.path];
            }
        },
        datapoint_title(datapoint) {
            return `${datapoint.basename} ${datapoint.session_id} ${datapoint.seq_num}`;
        },
        async deleteSelected() {
            // Filter out selected frames
            this.datapoints = this.datapoints.filter(datapoint => !this.selectedDatapoints[datapoint.path]);
            // Reset selection state for deleted frames
            this.selectedDatapoints = Object.fromEntries(
                this.datapoints.map(datapoint => [datapoint.path, false])
            );
        },
        async copyToFolder() {
            if (!this.targetFolder) {
                alert('Please enter a target folder name');
                return;
            }
            
            const selectedPaths = this.datapoints
                .filter(datapoint => this.selectedDatapoints[datapoint.path])
                .map(datapoint => datapoint.path);

            if (selectedPaths.length === 0) {
                alert('Please select datapoints to copy');
                return;
            }

            try {
                const response = await fetch('/api/copy-to-folder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        paths: selectedPaths,
                        target_folder: this.targetFolder
                    }),
                });

                if (!response.ok) {
                    throw new Error('Failed to copy datapoints');
                }

                // Navigate to the new folder
                this.$router.push(`/folder/${this.targetFolder}`);
            } catch (error) {
                alert('Error copying datapoints: ' + error.message);
            }
        },
        showModal(datapoint) {
            this.selectedImage = datapoint;
        },
        closeModal() {
            this.selectedImage = null;
        },
        toggleSelectionMode() {
            this.selectionMode = !this.selectionMode;
        },
        handleImageClick(datapoint) {
            if (this.selectionMode) {
                this.selectedDatapoints[datapoint.path] = !this.selectedDatapoints[datapoint.path];
            } else {
                this.showModal(datapoint);
            }
        },
        toggleDropdown() {
            if (!this.isAnalyzing) {
                this.showDropdown = !this.showDropdown;
            }
        },
        async analyzeImages() {
            this.showDropdown = false;
            this.isAnalyzing = true;
            try {
                for (var i in this.datapoints) {
                    const datapoint = this.datapoints[i];
                    const response = await fetch('/api/analyze', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(datapoint),
                    });
                    
                    const result = await response.json();
                    this.datapoints[i] = result;
                }
            } catch (error) {
                alert(`Error analyzing image: ${error}`);
            } finally {
                this.isAnalyzing = false;
            }
        },
        nextPage() {
            this.start += this.pageSize;
            this.reload();
        },
        previousPage() {
            this.start = Math.max(0, this.start - this.pageSize);
            this.reload();
        },
    },
}
</script>

<style>
.datapoint {
    position: relative;
    margin: 5px;
}

.datapoint-container {
    border: 1px solid green;
    padding: 5px;
    position: relative;
}

.datapoint input[type="checkbox"] {
    position: absolute;
    top: 10px;
    left: 10px;
    width: 30px;
    height: 30px;
    opacity: 0;
    z-index: 1;
    cursor: pointer;
    transition: opacity 0.2s;
}

.datapoint:hover input[type="checkbox"],
.datapoint input[type="checkbox"]:checked {
    opacity: 1;
}

.datapoint-image {
    height: v-bind(imageSize + 'px');
    display: block;
}
div.datapoints {
    display: flex;
    flex-wrap: wrap;
}
div.datapoints img {
    margin: 5px;
}
.selection-controls {
    margin: 10px 0;
}
.selection-controls button {
    margin-right: 10px;
}
.delete-button {
    background-color: #ff4444;
    color: white;
}
.selection-controls input {
    margin-right: 10px;
    padding: 5px;
}
.size-control {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    margin-left: 10px;
}

.size-control input[type="range"] {
    width: 150px;
}

/* Add modal styles */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    cursor: pointer;
}

.modal-image {
    max-width: 90%;
    max-height: 90vh;
    object-fit: contain;
}

.mode-button {
    background-color: #666;
    color: white;
}

.mode-button.active {
    background-color: #4CAF50;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-button {
    background-color: #2196F3;
    color: white;
}

.dropdown-button:disabled {
    background-color: #90CAF9;
    cursor: not-allowed;
}

.dropdown-content {
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-radius: 4px;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {
    background-color: #f1f1f1;
}

.qr-info {
    bottom: 5px;
    right: 5px;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 1rem;
    border-radius: 3px;
    font-size: 14px;
    width: 200px;
    text-wrap: wrap;
}

.qr-info > div {
    margin: 2px 0;
}

.pagination-controls {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-top: 1rem;
}

.pagination-controls button {
    padding: 0.5rem 1rem;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.pagination-controls button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
}

.pagination-controls select {
    padding: 0.5rem;
    border-radius: 4px;
}
</style>