{% extends "base.html" %}

{% block title %}Snapshots - AWS Inventory Browser{% endblock %}

{% block content %}
<div class="space-y-6" x-data="snapshotsPage()" x-init="loadInventories()">
    <div class="md:flex md:items-center md:justify-between">
        <div class="min-w-0 flex-1">
            <h1 class="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl">Snapshots</h1>
        </div>
        <div class="mt-4 flex md:ml-4 md:mt-0">
            <button @click="showCreateModal = true"
                    class="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all">
                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/>
                </svg>
                Create Snapshot
            </button>
        </div>
    </div>

    <!-- Snapshots Grid -->
    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {% for snapshot in snapshots %}
        <div class="relative bg-white rounded-lg shadow hover:shadow-md transition-shadow">
            <div class="p-5">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-medium text-gray-900 truncate">
                        <a href="/snapshots/{{ snapshot.name }}" class="hover:text-blue-600">
                            {{ snapshot.name }}
                        </a>
                    </h3>
                    {% if snapshot.name == active_snapshot %}
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        Active
                    </span>
                    {% endif %}
                </div>

                <div class="mt-4 space-y-2">
                    <div class="flex items-center text-sm text-gray-500">
                        <svg class="flex-shrink-0 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
                        </svg>
                        {{ snapshot.resource_count | format_number }} resources
                    </div>
                    <div class="flex items-center text-sm text-gray-500">
                        <svg class="flex-shrink-0 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                        </svg>
                        {{ snapshot.created_at }}
                    </div>
                    <div class="flex items-center text-sm text-gray-500">
                        <svg class="flex-shrink-0 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                        </svg>
                        {{ snapshot.regions | join(', ') if snapshot.regions else 'N/A' }}
                    </div>
                </div>

                <div class="mt-4 flex space-x-2">
                    <a href="/snapshots/{{ snapshot.name }}"
                       class="flex-1 text-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                        View
                    </a>
                    {% if snapshot.name != active_snapshot %}
                    <button hx-post="/api/snapshots/{{ snapshot.name }}/activate"
                            hx-swap="none"
                            hx-on::after-request="window.location.reload()"
                            class="flex-1 text-center px-3 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
                        Set Active
                    </button>
                    {% endif %}
                </div>

                <!-- Action buttons -->
                <div class="mt-3 pt-3 border-t border-gray-100 flex space-x-2">
                    <button @click="openRenameModal('{{ snapshot.name }}')"
                            class="flex-1 text-center px-3 py-1.5 text-xs font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded transition-colors">
                        <svg class="inline w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                        </svg>
                        Rename
                    </button>
                    {% if snapshot.name != active_snapshot %}
                    <button @click="confirmDelete('{{ snapshot.name }}')"
                            class="flex-1 text-center px-3 py-1.5 text-xs font-medium text-red-600 hover:text-red-800 hover:bg-red-50 rounded transition-colors">
                        <svg class="inline w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                        </svg>
                        Delete
                    </button>
                    {% endif %}
                </div>
            </div>
        </div>
        {% else %}
        <div class="col-span-full text-center py-12">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"/>
            </svg>
            <h3 class="mt-2 text-sm font-medium text-gray-900">No snapshots</h3>
            <p class="mt-1 text-sm text-gray-500">Create your first snapshot with the CLI:</p>
            <code class="mt-2 inline-block bg-gray-100 px-4 py-2 rounded text-sm">
                awsinv snapshot create my-baseline --regions us-east-1
            </code>
        </div>
        {% endfor %}
    </div>

    <!-- Create Snapshot Modal -->
    <div x-show="showCreateModal" class="fixed z-50 inset-0 overflow-y-auto" x-cloak>
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm transition-opacity" @click="showCreateModal = false"></div>

            <div class="relative bg-white rounded-xl shadow-2xl max-w-lg w-full overflow-hidden"
                 x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 scale-95"
                 x-transition:enter-end="opacity-100 scale-100">
                <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-5">
                    <h3 class="text-xl font-bold text-white">Create New Snapshot</h3>
                    <p class="text-blue-100 text-sm mt-1">Capture current state of AWS resources</p>
                </div>

                <form @submit.prevent="createSnapshot" class="p-6 space-y-5">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Snapshot Name</label>
                        <input type="text" x-model="newSnapshot.name"
                               class="w-full border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                               placeholder="Auto-generated if empty">
                        <p class="text-xs text-gray-500 mt-1">Leave empty to auto-generate (snapshot-YYYYMMDD-HHMMSS)</p>
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Inventory</label>
                        <select x-model="newSnapshot.inventory"
                                class="w-full border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500">
                            <option value="">-- No inventory (collect all) --</option>
                            <template x-for="inv in inventories" :key="inv.name">
                                <option :value="inv.name" x-text="inv.name + (inv.description ? ' - ' + inv.description : '')"></option>
                            </template>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">Use inventory filters (include/exclude tags)</p>
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Regions</label>
                        <input type="text" x-model="newSnapshot.regions"
                               class="w-full border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                               placeholder="us-east-1">
                        <p class="text-xs text-gray-500 mt-1">Comma-separated list (default: us-east-1)</p>
                    </div>

                    <div class="flex items-center space-x-4">
                        <label class="flex items-center">
                            <input type="checkbox" x-model="newSnapshot.setActive"
                                   class="h-4 w-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">Set as active snapshot</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" x-model="newSnapshot.useConfig"
                                   class="h-4 w-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">Use AWS Config</span>
                        </label>
                    </div>

                    <!-- Job Status -->
                    <div x-show="createJobId" class="p-4 bg-blue-50 rounded-lg border border-blue-200">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-blue-700">Status:</span>
                            <span class="text-sm font-semibold"
                                  :class="{
                                      'text-yellow-600': createJobStatus === 'pending' || createJobStatus === 'running',
                                      'text-green-600': createJobStatus === 'completed',
                                      'text-red-600': createJobStatus === 'failed'
                                  }"
                                  x-text="createJobStatus"></span>
                        </div>
                        <p class="text-sm text-gray-600" x-text="createJobMessage"></p>
                        <div x-show="createJobProgress > 0" class="mt-2">
                            <div class="w-full bg-blue-100 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                                     :style="'width: ' + createJobProgress + '%'"></div>
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-3 pt-2">
                        <button type="button" @click="showCreateModal = false; resetCreateForm()"
                                class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                                :disabled="creating">
                            <span x-text="createJobStatus === 'completed' ? 'Close' : 'Cancel'"></span>
                        </button>
                        <button type="submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 rounded-lg transition-colors"
                                :disabled="creating || createJobId"
                                x-show="!createJobId">
                            <span x-show="!creating">Create Snapshot</span>
                            <span x-show="creating" class="flex items-center justify-center">
                                <svg class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                </svg>
                                Starting...
                            </span>
                        </button>
                        <button type="button" @click="window.location.reload()"
                                class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-lg transition-colors"
                                x-show="createJobStatus === 'completed'">
                            View Snapshot
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Rename Modal -->
    <div x-show="showRenameModal" class="fixed z-50 inset-0 overflow-y-auto" x-cloak>
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm transition-opacity" @click="showRenameModal = false"></div>

            <div class="relative bg-white rounded-xl shadow-2xl max-w-md w-full overflow-hidden"
                 x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 scale-95"
                 x-transition:enter-end="opacity-100 scale-100">
                <div class="bg-gradient-to-r from-blue-500 to-indigo-600 px-6 py-4">
                    <h3 class="text-lg font-bold text-white">Rename Snapshot</h3>
                </div>

                <form @submit.prevent="renameSnapshot" class="p-6 space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Current Name</label>
                        <input type="text" :value="renameOldName" disabled
                               class="w-full bg-gray-100 border-gray-300 rounded-lg text-gray-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">New Name</label>
                        <input type="text" x-model="renameNewName" required
                               class="w-full border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500"
                               placeholder="Enter new name">
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="button" @click="showRenameModal = false"
                                class="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors">
                            Cancel
                        </button>
                        <button type="submit" class="flex-1 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
                                :disabled="renaming">
                            <span x-show="!renaming">Rename</span>
                            <span x-show="renaming">Renaming...</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function snapshotsPage() {
    return {
        // Rename modal
        showRenameModal: false,
        renameOldName: '',
        renameNewName: '',
        renaming: false,

        // Create modal
        showCreateModal: false,
        creating: false,
        inventories: [],
        newSnapshot: {
            name: '',
            inventory: '',
            regions: 'us-east-1',
            setActive: true,
            useConfig: true
        },
        createJobId: null,
        createJobStatus: null,
        createJobMessage: '',
        createJobProgress: 0,
        pollInterval: null,

        async loadInventories() {
            try {
                const response = await fetch('/api/inventories');
                if (response.ok) {
                    const data = await response.json();
                    this.inventories = data.inventories || [];
                }
            } catch (error) {
                console.error('Failed to load inventories:', error);
            }
        },

        resetCreateForm() {
            this.newSnapshot = {
                name: '',
                inventory: '',
                regions: 'us-east-1',
                setActive: true,
                useConfig: true
            };
            this.createJobId = null;
            this.createJobStatus = null;
            this.createJobMessage = '';
            this.createJobProgress = 0;
            if (this.pollInterval) {
                clearInterval(this.pollInterval);
                this.pollInterval = null;
            }
        },

        async createSnapshot() {
            this.creating = true;
            try {
                const regions = this.newSnapshot.regions
                    ? this.newSnapshot.regions.split(',').map(r => r.trim()).filter(r => r)
                    : ['us-east-1'];

                const response = await fetch('/api/snapshots', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name: this.newSnapshot.name || null,
                        inventory: this.newSnapshot.inventory || null,
                        regions: regions,
                        set_active: this.newSnapshot.setActive,
                        use_config: this.newSnapshot.useConfig
                    })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || 'Failed to create snapshot');
                }

                const result = await response.json();
                this.createJobId = result.job_id;
                this.createJobStatus = 'pending';
                this.createJobMessage = result.message;

                // Start polling for status
                this.pollJobStatus();

            } catch (error) {
                alert('Error: ' + error.message);
            } finally {
                this.creating = false;
            }
        },

        pollJobStatus() {
            this.pollInterval = setInterval(async () => {
                try {
                    const response = await fetch('/api/snapshots/jobs/' + this.createJobId);
                    if (response.ok) {
                        const status = await response.json();
                        this.createJobStatus = status.status;
                        this.createJobMessage = status.message;
                        this.createJobProgress = status.progress || 0;

                        if (status.status === 'completed' || status.status === 'failed') {
                            clearInterval(this.pollInterval);
                            this.pollInterval = null;
                        }
                    }
                } catch (error) {
                    console.error('Failed to poll job status:', error);
                }
            }, 2000);
        },

        openRenameModal(name) {
            this.renameOldName = name;
            this.renameNewName = name;
            this.showRenameModal = true;
        },

        async renameSnapshot() {
            if (!this.renameNewName || this.renameNewName === this.renameOldName) return;

            this.renaming = true;
            try {
                const response = await fetch('/api/snapshots/' + encodeURIComponent(this.renameOldName) + '/rename', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ new_name: this.renameNewName })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || 'Failed to rename snapshot');
                }

                window.location.reload();
            } catch (error) {
                alert('Error: ' + error.message);
            } finally {
                this.renaming = false;
            }
        },

        async confirmDelete(name) {
            if (!confirm('Are you sure you want to delete snapshot "' + name + '"? This cannot be undone.')) return;

            try {
                const response = await fetch('/api/snapshots/' + encodeURIComponent(name), {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || 'Failed to delete snapshot');
                }

                window.location.reload();
            } catch (error) {
                alert('Error: ' + error.message);
            }
        }
    };
}
</script>
{% endblock %}
