{% extends "base.html" %}

{% block title %}Consumption Sheets - ScanLook{% endblock %}

{% block content %}
<div class="dashboard-container">
    <div class="page-header">
        <div>
            <a href="{{ url_for('home') }}" class="breadcrumb">← Back to Home</a>
            <h1 class="page-title">Consumption Sheets</h1>
            <p class="page-subtitle">Scan and record lot consumption</p>
        </div>
    </div>

    <!-- New Session Button -->
    <div class="new-session-section">
        <h2 class="section-title">Start New Session</h2>
        <div class="process-buttons">
            {% for p in processes %}
            <a href="{{ url_for('conssheets.new_session', process_id=p.id) }}" class="btn btn-primary">
                <span class="btn-icon">+</span> {{ p.process_name }}
            </a>
            {% endfor %}
            {% if not processes %}
            <p class="empty-text">No process types configured yet. Contact your administrator.</p>
            {% endif %}
        </div>
    </div>

    <!-- Active Sessions -->
    {% if sessions %}
    <div class="section-card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--space-md);">
            <h2 class="section-title">📋 My Sessions</h2>
            <label class="checkbox-toggle">
                <input type="checkbox" id="showArchivedToggle" {% if show_archived %}checked{% endif %} onchange="toggleArchived(this.checked)">
                <span>Show archived/deleted</span>
            </label>
        </div>
        <div class="sessions-list">
            {% for s in sessions %}
            <div class="session-list-item-container session-status-{{ s.status }}">
                <a href="{{ url_for('conssheets.scan_session', session_id=s.id) }}" class="session-list-item">
                    <div class="session-list-info">
                        <h3 class="session-list-name">{{ s.session_title }}</h3>
                        <div class="session-list-meta">
                            <span>Started: {{ s.created_at[:16] }}</span>
                            <span>•</span>
                            <span>{{ s.scan_count or 0 }} Scanned</span>
                        </div>
                        {% if s.header_preview %}
                        <div class="session-list-meta" style="margin-top: var(--space-xs); font-size: 0.8rem;">
                            {% for hf in s.header_preview %}
                            <span><strong>{{ hf.field_label }}:</strong> {{ hf.field_value or '—' }}</span>
                            {% if not loop.last %}<span>•</span>{% endif %}
                            {% endfor %}
                        </div>
                        {% endif %}
                        {% if s.status == 'archived' %}
                        <div class="session-list-meta" style="margin-top: var(--space-xs);">
                            <span style="color: var(--color-warning);">📦 Archived</span>
                        </div>
                        {% elif s.status == 'deleted' %}
                        <div class="session-list-meta" style="margin-top: var(--space-xs);">
                            <span style="color: var(--color-danger);">🗑️ Deleted</span>
                        </div>
                        {% endif %}
                    </div>
                    <div class="session-list-action">
                        <span class="arrow-icon">→</span>
                    </div>
                </a>
                
                {% if s.status == 'active' %}
                    <button class="btn-session-action btn-archive" onclick="archiveSession({{ s.id }}, '{{ s.process_name }}')" title="Archive this session">
                        📦
                    </button>
                    {% if session.role in ['owner', 'admin'] %}
                    <button class="btn-session-action btn-delete" onclick="deleteSession({{ s.id }}, '{{ s.process_name }}')" title="Delete this session">
                        ❌
                    </button>
                    {% endif %}
                {% elif s.status == 'archived' %}
                    <button class="btn-session-action btn-unarchive" onclick="unarchiveSession({{ s.id }}, '{{ s.process_name }}')" title="Restore to active">
                        ↩️
                    </button>
                    {% if session.role in ['owner', 'admin'] %}
                    <button class="btn-session-action btn-delete" onclick="deleteSession({{ s.id }}, '{{ s.process_name }}')" title="Delete this session">
                        ❌
                    </button>
                    {% endif %}
                {% elif s.status == 'deleted' and session.role in ['owner', 'admin'] %}
                    <button class="btn-session-action btn-restore" onclick="restoreSession({{ s.id }}, '{{ s.process_name }}')" title="Restore from deleted">
                        🔄
                    </button>
                {% endif %}
            </div>
            {% endfor %}
        </div>
    </div>
    {% else %}
    <div class="empty-state">
        <div class="empty-icon">📝</div>
        <h2 class="empty-title">No Active Sessions</h2>
        <p class="empty-text">Start a new session by selecting a process type above</p>
    </div>
    {% endif %}
</div>

<!-- Styles moved to static/css/style.css for maintainability -->
<script>
function toggleArchived(checked) {
    const url = new URL(window.location.href);
    if (checked) {
        url.searchParams.set('show_archived', '1');
    } else {
        url.searchParams.delete('show_archived');
    }
    window.location.href = url.toString();
}

function archiveSession(sessionId, processName) {
    if (!confirm(`Archive this ${processName} session?\n\nYou can restore it later.`)) {
        return;
    }
    
    fetch(`/conssheets/session/${sessionId}/archive`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Error archiving session');
        }
    });
}

function unarchiveSession(sessionId, processName) {
    if (!confirm(`Restore ${processName} session to active?`)) {
        return;
    }
    
    fetch(`/conssheets/session/${sessionId}/unarchive`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Error restoring session');
        }
    });
}

function deleteSession(sessionId, processName) {
    if (!confirm(`⚠️ DELETE ${processName} session?\n\nThis will mark all scanned data as deleted.\nThis action cannot be undone easily.\n\nAre you absolutely sure?`)) {
        return;
    }
    
    fetch(`/conssheets/session/${sessionId}/delete`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Error deleting session');
        }
    });
}

function restoreSession(sessionId, processName) {
    if (!confirm(`Restore ${processName} from deleted?\n\nThis will reactivate the session and all its data.`)) {
        return;
    }
    
    fetch(`/conssheets/session/${sessionId}/restore`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'}
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Error restoring session');
        }
    });
}
</script>
{% endblock %}
