{% extends "base.html" %}
{% from "components/ui.html" import page_header, empty_state %}

{% block title %}{{ _('Scheduled Reports') }} - {{ app_name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Reports', 'url': url_for('reports.reports')},
    {'text': 'Scheduled Reports'}
] %}

{{ page_header(
    icon_class='fas fa-clock',
    title_text='Scheduled Reports',
    subtitle_text='Automated report delivery via email',
    breadcrumbs=breadcrumbs,
    actions_html='<a href="' + url_for("scheduled_reports.create_scheduled") + '" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"><i class="fas fa-plus mr-2"></i>Schedule Report</a>'
) }}

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
    {% if schedules %}
    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-border-light dark:divide-border-dark responsive-cards">
            <thead>
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Report') }}</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Recipients') }}</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Frequency') }}</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Next Run') }}</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Status') }}</th>
                    <th class="px-6 py-3 text-right text-xs font-medium text-text-muted-light dark:text-text-muted-dark uppercase tracking-wider">{{ _('Actions') }}</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-border-light dark:divide-border-dark">
                {% for schedule in schedules %}
                <tr class="hover:bg-gray-50 dark:hover:bg-gray-800">
                    <td class="px-6 py-4 whitespace-nowrap" data-label="{{ _('Report') }}">
                        <div class="font-medium">{{ schedule.saved_view.name if schedule.saved_view else _('Unknown') }}</div>
                        {% if schedule.split_by_salesman and schedule.salesman_field_name %}
                        <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">
                            <i class="fas fa-sync-alt mr-1"></i>{{ _('Split by') }}: {{ schedule.salesman_field_name }}
                        </div>
                        {% endif %}
                        {% if schedule.email_distribution_mode and schedule.email_distribution_mode != 'single' %}
                        <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">
                            <i class="fas fa-envelope mr-1"></i>{{ _('Distribution') }}: {{ schedule.email_distribution_mode|title }}
                        </div>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4" data-label="{{ _('Recipients') }}">
                        <div class="text-sm">{{ schedule.recipients }}</div>
                        {% if schedule.recipient_email_template %}
                        <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">
                            {{ _('Template') }}: {{ schedule.recipient_email_template }}
                        </div>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap" data-label="{{ _('Frequency') }}">
                        <span class="px-2 py-1 text-xs rounded bg-primary/10 text-primary">{{ schedule.cadence|title }}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap" data-label="{{ _('Next Run') }}">
                        {% if schedule.next_run_at %}
                        <div class="text-sm">{{ schedule.next_run_at|user_datetime }}</div>
                        {% else %}
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Not scheduled') }}</span>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap" data-label="{{ _('Status') }}">
                        {% if not schedule.saved_view %}
                        <span class="px-2 py-1 text-xs rounded bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200" title="{{ _('Invalid: saved view not found') }}">
                            <i class="fas fa-exclamation-triangle mr-1"></i>{{ _('Error') }}
                        </span>
                        {% elif schedule.active %}
                        <span class="px-2 py-1 text-xs rounded bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">{{ _('Active') }}</span>
                        {% else %}
                        <span class="px-2 py-1 text-xs rounded bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">{{ _('Inactive') }}</span>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium" data-label="{{ _('Actions') }}">
                        <div class="flex justify-end gap-2">
                            {% if schedule.saved_view and schedule.active %}
                            <button 
                                type="button" 
                                class="trigger-report-btn text-blue-600 hover:text-blue-800" 
                                data-schedule-id="{{ schedule.id }}"
                                title="{{ _('Trigger report now (for testing)') }}">
                                <i class="fas fa-play"></i>
                            </button>
                            {% endif %}
                            {% if not schedule.saved_view %}
                            <form method="POST" action="{{ url_for('scheduled_reports.fix_scheduled', schedule_id=schedule.id) }}" class="inline">
                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                <button type="submit" class="text-yellow-600 hover:text-yellow-800" title="{{ _('Fix or remove invalid schedule') }}">
                                    <i class="fas fa-wrench"></i>
                                </button>
                            </form>
                            {% endif %}
                            <form method="POST" action="{{ url_for('scheduled_reports.delete_scheduled', schedule_id=schedule.id) }}" class="inline" onsubmit="return confirm('{{ _('Are you sure you want to delete this scheduled report?') }}')">
                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                <button type="submit" class="text-red-600 hover:text-red-800" title="{{ _('Delete') }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% else %}
    {{ empty_state(
        'fas fa-clock',
        _('No Scheduled Reports'),
        _('Create scheduled reports to automatically receive reports via email.'),
        actions_html='<a href="' + url_for('scheduled_reports.create_scheduled') + '" class="btn btn-primary">' + _('Schedule Report') + '</a>'
    ) }}
    {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const triggerButtons = document.querySelectorAll('.trigger-report-btn');
    
    triggerButtons.forEach(button => {
        button.addEventListener('click', function() {
            const scheduleId = this.getAttribute('data-schedule-id');
            const originalIcon = this.innerHTML;
            
            // Disable button and show loading state
            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            
            // Get CSRF token from meta tag or form
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                            document.querySelector('input[name="csrf_token"]')?.value || 
                            '{{ csrf_token() }}';
            
            // Make API call
            fetch(`/api/reports/scheduled/${scheduleId}/trigger`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    alert('{{ _("Report triggered successfully!") }}\n' + 
                          (data.message || '{{ _("Report sent to recipients.") }}'));
                } else {
                    // Show error message
                    alert('{{ _("Error triggering report:") }}\n' + (data.error || data.message || '{{ _("Unknown error") }}'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('{{ _("Error triggering report. Please check the console for details.") }}');
            })
            .finally(() => {
                // Re-enable button and restore icon
                this.disabled = false;
                this.innerHTML = originalIcon;
            });
        });
    });
});
</script>
{% endblock %}

