{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}{% trans "Survey Analytics Reports" %} - PX360{% endblock %}

{% block content %}
<!-- Header -->
<header class="mb-6">
    <div class="flex justify-between items-start">
        <div>
            <h1 class="text-2xl font-bold text-navy">
                <i data-lucide="file-bar-chart" class="w-6 h-6 inline-block mr-2"></i>
                {% trans "Survey Analytics Reports" %}
            </h1>
            <p class="text-sm text-slate mt-1">{% trans "Comprehensive survey performance analysis with statistical insights" %}</p>
        </div>
        <div class="flex gap-3">
            <a href="{% url 'surveys:enhanced_reports_list' %}" 
               class="bg-emerald-500 text-white px-6 py-3 rounded-xl font-semibold hover:bg-emerald-600 transition flex items-center gap-2">
                <i data-lucide="bar-chart-3" class="w-5 h-5"></i> {% trans "Enhanced Reports" %}
            </a>
            <button class="bg-navy text-white px-6 py-3 rounded-xl font-semibold hover:bg-navy transition flex items-center gap-2" 
                    onclick="document.getElementById('generateReportModal').classList.remove('hidden')">
                <i data-lucide="file-plus" class="w-5 h-5"></i> {% trans "Generate Report" %}
            </button>
        </div>
    </div>
</header>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white p-6 rounded-[2rem] shadow-sm border border-gray-50">
            <div class="flex justify-between items-start mb-4">
                <div class="bg-blue-100 p-3 rounded-full">
                    <i data-lucide="files" class="text-blue-500 w-6 h-6"></i>
                </div>
                <span class="text-blue-500 text-sm font-bold bg-blue-50 px-2 py-1 rounded-lg">
                    {% trans "Total" %}
                </span>
            </div>
            <div class="text-4xl font-bold mb-1">{{ stats.total }}</div>
            <div class="text-gray-400 text-sm font-medium">{% trans "Reports" %}</div>
        </div>

        <div class="bg-white p-6 rounded-[2rem] shadow-sm border border-gray-50">
            <div class="flex justify-between items-start mb-4">
                <div class="bg-cyan-100 p-3 rounded-full">
                    <i data-lucide="file-code" class="text-cyan-500 w-6 h-6"></i>
                </div>
                <span class="text-cyan-500 text-sm font-bold bg-cyan-50 px-2 py-1 rounded-lg">
                    JSON
                </span>
            </div>
            <div class="text-4xl font-bold mb-1 text-cyan-600">{{ stats.json }}</div>
            <div class="text-gray-400 text-sm font-medium">{% trans "Reports" %}</div>
        </div>

        <div class="bg-white p-6 rounded-[2rem] shadow-sm border border-gray-50">
            <div class="flex justify-between items-start mb-4">
                <div class="bg-emerald-100 p-3 rounded-full">
                    <i data-lucide="file-text" class="text-emerald-500 w-6 h-6"></i>
                </div>
                <span class="text-emerald-500 text-sm font-bold bg-emerald-50 px-2 py-1 rounded-lg">
                    HTML
                </span>
            </div>
            <div class="text-4xl font-bold mb-1 text-emerald-600">{{ stats.html }}</div>
            <div class="text-gray-400 text-sm font-medium">{% trans "Reports" %}</div>
        </div>

        <div class="bg-white p-6 rounded-[2rem] shadow-sm border border-gray-50">
            <div class="flex justify-between items-start mb-4">
                <div class="bg-amber-100 p-3 rounded-full">
                    <i data-lucide="file-richtext" class="text-amber-500 w-6 h-6"></i>
                </div>
                <span class="text-amber-500 text-sm font-bold bg-amber-50 px-2 py-1 rounded-lg">
                    {% trans "Markdown" %}
                </span>
            </div>
            <div class="text-4xl font-bold mb-1 text-amber-600">{{ stats.markdown }}</div>
            <div class="text-gray-400 text-sm font-medium">{% trans "Reports" %}</div>
        </div>
    </div>

    <!-- Reports Table -->
    <div class="bg-white rounded-2xl shadow-sm border border-gray-50 overflow-hidden">
        <div class="p-6 border-b border-gray-100">
            <h3 class="font-bold text-gray-800 flex items-center gap-2">
                <i data-lucide="folder" class="w-5 h-5 text-navy"></i>
                {% trans "Available Reports" %}
            </h3>
        </div>
        <div class="p-6">
            {% if reports %}
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Filename" %}</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Type" %}</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Size" %}</th>
                            <th class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Created" %}</th>
                            <th class="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase tracking-wider">{% trans "Actions" %}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        {% for report in reports %}
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-2">
                                    <i data-lucide="file" class="w-5 h-5 text-gray-400"></i>
                                    <strong class="text-gray-800">{{ report.filename }}</strong>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                {% if report.type == 'json' %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-cyan-100 text-cyan-700">JSON</span>
                                {% elif report.type == 'html' %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-700">HTML</span>
                                {% elif report.type == 'markdown' %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-amber-100 text-amber-700">Markdown</span>
                                {% else %}
                                <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-gray-100 text-gray-700">{{ report.type|title }}</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4 text-gray-600">{{ report.size_human }}</td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-800">{{ report.created_date|date:"M d, Y" }}</div>
                                <div class="text-xs text-gray-400">{{ report.created_date|time:"H:i" }}</div>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2">
                                    <a href="{% url 'surveys:analytics_report_view_inline' report.filename %}" 
                                       class="inline-flex items-center gap-1 px-3 py-2 text-blue-500 bg-blue-50 rounded-lg hover:bg-blue-100 transition font-medium text-sm"
                                       title="{% trans 'View' %}"
                                       target="_blank">
                                        <i data-lucide="eye" class="w-4 h-4"></i>
                                    </a>
                                    <a href="{% url 'surveys:analytics_report_download' report.filename %}" 
                                       class="inline-flex items-center gap-1 px-3 py-2 text-emerald-500 bg-emerald-50 rounded-lg hover:bg-emerald-100 transition font-medium text-sm"
                                       title="{% trans 'Download' %}">
                                        <i data-lucide="download" class="w-4 h-4"></i>
                                    </a>
                                    <form method="post" 
                                          action="{% url 'surveys:analytics_report_delete' report.filename %}"
                                          class="inline"
                                          onsubmit="return confirm('{% trans "Are you sure you want to delete this report?" %}')">
                                        {% csrf_token %}
                                        <button type="submit" class="inline-flex items-center gap-1 px-3 py-2 text-red-500 bg-red-50 rounded-lg hover:bg-red-100 transition font-medium text-sm"
                                                title="{% trans 'Delete' %}">
                                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% else %}
            <div class="text-center py-16">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-gray-100 rounded-full mb-4">
                    <i data-lucide="file-x" class="w-10 h-10 text-gray-400"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-800 mb-2">{% trans "No Reports Found" %}</h3>
                <p class="text-gray-500 mb-4">
                    {% trans "Generate your first comprehensive survey analytics report." %}
                </p>
                <button class="bg-navy text-white px-6 py-3 rounded-xl font-semibold hover:bg-navy transition flex items-center gap-2 mx-auto" 
                        onclick="document.getElementById('generateReportModal').classList.remove('hidden')">
                    <i data-lucide="file-plus" class="w-5 h-5"></i> {% trans "Generate Report" %}
                </button>
            </div>
            {% endif %}
        </div>
    </div>

<!-- Generate Report Modal -->
<div id="generateReportModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
            <h3 class="text-xl font-bold text-gray-800 flex items-center gap-2">
                <i data-lucide="settings" class="w-6 h-6 text-navy"></i>
                {% trans "Generate Analytics Report" %}
            </h3>
            <button onclick="document.getElementById('generateReportModal').classList.add('hidden')" 
                    class="text-gray-400 hover:text-gray-600 transition">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>
        <form id="generateReportForm">
            <div class="p-6 space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Survey Template -->
                    <div>
                        <label for="template" class="block text-sm font-bold text-gray-700 mb-2">{% trans "Survey Template" %}</label>
                        <select name="template" id="template" 
                                class="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl text-gray-800 focus:ring-2 focus:ring-navy focus:border-transparent transition">
                            <option value="">{% trans "All Templates" %}</option>
                        </select>
                    </div>
                    
                    <!-- Output Format -->
                    <div>
                        <label for="format" class="block text-sm font-bold text-gray-700 mb-2">{% trans "Output Format" %}</label>
                        <select name="format" id="format" 
                                class="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl text-gray-800 focus:ring-2 focus:ring-navy focus:border-transparent transition">
                            <option value="json">JSON</option>
                            <option value="html">HTML</option>
                            <option value="markdown">Markdown</option>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Start Date -->
                    <div>
                        <label for="start_date" class="block text-sm font-bold text-gray-700 mb-2">{% trans "Start Date" %}</label>
                        <input type="date" name="start_date" id="start_date" 
                               class="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl text-gray-800 focus:ring-2 focus:ring-navy focus:border-transparent transition">
                    </div>
                    
                    <!-- End Date -->
                    <div>
                        <label for="end_date" class="block text-sm font-bold text-gray-700 mb-2">{% trans "End Date" %}</label>
                        <input type="date" name="end_date" id="end_date" 
                               class="w-full px-4 py-2.5 border-2 border-gray-200 rounded-xl text-gray-800 focus:ring-2 focus:ring-navy focus:border-transparent transition">
                    </div>
                </div>
                
                <div class="flex items-center gap-3 p-4 bg-gray-50 rounded-xl">
                    <input type="checkbox" name="save" id="save" checked
                           class="w-5 h-5 text-navy border-gray-300 rounded focus:ring-navy">
                    <label for="save" class="text-sm font-medium text-gray-700">
                        {% trans "Save report to server for later access" %}
                    </label>
                </div>
            </div>
            <div class="p-6 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" 
                        onclick="document.getElementById('generateReportModal').classList.add('hidden')"
                        class="px-6 py-2.5 border-2 border-gray-200 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition">
                    {% trans "Cancel" %}
                </button>
                <button type="submit" id="generateBtn"
                        class="px-6 py-2.5 bg-navy text-white rounded-xl font-semibold hover:bg-navy transition flex items-center gap-2">
                    <i data-lucide="settings" class="w-4 h-4"></i> {% trans "Generate" %}
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // Load survey templates
    fetch('/surveys/api/templates/')
        .then(response => response.json())
        .then(data => {
            const templateSelect = document.getElementById('template');
            data.results.forEach(template => {
                const option = document.createElement('option');
                option.value = template.name;
                option.textContent = template.name;
                templateSelect.appendChild(option);
            });
        })
        .catch(error => console.error('Error loading templates:', error));
    
    // Handle form submission
    document.getElementById('generateReportForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const btn = document.getElementById('generateBtn');
        const originalHTML = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = `
            <svg class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {% trans "Generating..." %}
        `;
        
        const formData = new FormData(this);
        const data = {};
        formData.forEach((value, key) => {
            if (value) {
                if (key === 'save') {
                    data[key] = true;
                } else {
                    data[key] = value;
                }
            }
        });
        
        fetch('/surveys/api/analytics/generate_report/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(result => {
            btn.disabled = false;
            btn.innerHTML = originalHTML;
            
            if (result.success) {
                document.getElementById('generateReportModal').classList.add('hidden');
                
                if (result.content) {
                    const blob = new Blob([result.content], { type: 'text/html' });
                    const url = URL.createObjectURL(blob);
                    window.open(url, '_blank');
                } else if (result.data) {
                    const blob = new Blob([JSON.stringify(result.data, null, 2)], { type: 'application/json' });
                    const url = URL.createObjectURL(blob);
                    window.open(url, '_blank');
                }
                
                location.reload();
            } else {
                alert('Error: ' + (result.error || 'Failed to generate report'));
            }
        })
        .catch(error => {
            btn.disabled = false;
            btn.innerHTML = originalHTML;
            alert('Error: ' + error.message);
        });
    });
});
</script>
{% endblock %}