{% extends "base.html" %}

{% block title %}{{ _('Generate Invoice from Time') }} - TimeTracker{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <!-- Enhanced Header -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div class="d-flex align-items-center">
                    <h1 class="h3 mb-0 me-3">
                        <i class="fas fa-clock text-primary"></i>
                        {{ _('Generate Invoice Items from Time Entries') }}
                    </h1>
                    <span class="badge bg-info fs-6">{{ _('Invoice #') }}{{ invoice.invoice_number }}</span>
                </div>
                <a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i> {{ _('Back to Invoice') }}
                </a>
            </div>

            <!-- Invoice Summary Card -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card shadow-sm border-0">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="summary-item">
                                        <div class="summary-label">{{ _('Client') }}</div>
                                        <div class="summary-value">{{ invoice.client_name }}</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="summary-item">
                                        <div class="summary-label">{{ _('Project') }}</div>
                                        <div class="summary-value">{{ invoice.project.name }}</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="summary-item">
                                        <div class="summary-label">{{ _('Hourly Rate') }}</div>
                                        <div class="summary-value">{{ "%.2f"|format(invoice.project.hourly_rate or 0) }} {{ currency }}</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="summary-item">
                                        <div class="summary-label">{{ _('Available Hours') }}</div>
                                        <div class="summary-value text-primary">{{ "%.2f"|format(total_available_hours) }}h</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-8">
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-white py-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="m-0 font-weight-bold text-primary">
                                    <i class="fas fa-list me-2"></i>{{ _('Select Time Entries') }}
                                </h6>
                                <div class="d-flex gap-2">
                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectRecentEntries()">
                                        <i class="fas fa-calendar-week me-1"></i> {{ _('Last 7 Days') }}
                                    </button>
                                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectThisMonth()">
                                        <i class="fas fa-calendar-alt me-1"></i> {{ _('This Month') }}
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            {% if time_entries %}
                                <form method="POST" id="timeEntriesForm">
                                    <!-- Selection Controls -->
                                    <div class="selection-controls mb-4">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleAllEntries()">
                                                <label class="form-check-label fw-bold" for="selectAll">
                                                    {{ _('Select All Time Entries') }}
                                                </label>
                                            </div>
                                            <div class="selection-summary">
                                                <span class="badge bg-primary me-2">
                                                    <i class="fas fa-check me-1"></i>
                                                    <span id="selectedCount">0</span> {{ _('selected') }}
                                                </span>
                                                <span class="badge bg-success">
                                                    <i class="fas fa-clock me-1"></i>
                                                    <span id="totalHours">0.00</span> {{ _('hours') }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Time Entries Table -->
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th style="width: 5%">{{ _('Select') }}</th>
                                                    <th style="width: 15%">{{ _('Date') }}</th>
                                                    <th style="width: 20%">{{ _('User') }}</th>
                                                    <th style="width: 25%">{{ _('Task') }}</th>
                                                    <th style="width: 15%">{{ _('Duration') }}</th>
                                                    <th style="width: 20%">{{ _('Notes') }}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {% for entry in time_entries %}
                                                <tr class="time-entry-row" data-duration="{{ entry.duration_hours }}" data-task="{{ entry.task.name if entry.task else 'Project: ' + entry.project.name }}">
                                                    <td>
                                                        <div class="form-check">
                                                            <input class="form-check-input time-entry-checkbox" type="checkbox" 
                                                                   name="time_entries[]" value="{{ entry.id }}" 
                                                                   data-duration="{{ entry.duration_hours }}"
                                                                   data-task="{{ entry.task.name if entry.task else 'Project: ' + entry.project.name }}">
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="date-info">
                                                            <div class="date-value">{{ entry.start_time.strftime('%b %d') }}</div>
                                                            <small class="text-muted">{{ entry.start_time.strftime('%Y') }}</small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="user-info">
                                                            <div class="user-name">{{ entry.user.display_name }}</div>
                                                            <small class="text-muted">{{ entry.start_time.strftime('%I:%M %p') }}</small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        {% if entry.task %}
                                                            <span class="task-badge">{{ entry.task.name }}</span>
                                                        {% else %}
                                                            <span class="project-badge">{{ entry.project.name }}</span>
                                                        {% endif %}
                                                    </td>
                                                    <td>
                                                        <span class="duration-badge">{{ "%.2f"|format(entry.duration_hours) }}h</span>
                                                    </td>
                                                    <td>
                                                        {% if entry.notes %}
                                                            <div class="notes-content">
                                                                <div class="notes-text">{{ entry.notes[:50] }}{% if entry.notes|length > 50 %}...{% endif %}</div>
                                                                {% if entry.notes|length > 50 %}
                                                                <small class="text-muted">{{ _('Click to view full notes') }}</small>
                                                                {% endif %}
                                                            </div>
                                                        {% else %}
                                                            <span class="text-muted">{{ _('No notes') }}</span>
                                                        {% endif %}
                                                    </td>
                                                </tr>
                                                {% endfor %}
                                            </tbody>
                                        </table>
                                    </div>

                                    <!-- Summary Alert -->
                                    <div class="alert alert-info mt-4">
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-info-circle fa-lg me-3"></i>
                                            <div>
                                                <strong>{{ _('Summary:') }}</strong> 
                                                <span id="selectedCountText">0</span> {{ _('entries selected,') }} 
                                                <span id="totalHoursText">0.00</span> {{ _('hours total') }}
                                                <div class="mt-2">
                                                    <small class="text-muted">
                                                        {{ _("Selected entries will be converted to invoice line items with the project's hourly rate.") }}
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Action Buttons -->
                                    <div class="d-flex justify-content-between mt-4">
                                        <a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" class="btn btn-outline-secondary">
                                            <i class="fas fa-times me-1"></i> {{ _('Cancel') }}
                                        </a>
                                        <button type="submit" class="btn btn-primary btn-lg" id="generateBtn" disabled>
                                            <i class="fas fa-magic me-2"></i> {{ _('Generate Invoice Items') }}
                                        </button>
                                    </div>
                                </form>
                            {% else %}
                                <div class="text-center py-5">
                                    <div class="empty-state">
                                        <i class="fas fa-clock fa-3x text-muted mb-3"></i>
                                        <h5 class="text-muted">{{ _('No time entries found') }}</h5>
                                        <p class="text-muted mb-4">
                                            {{ _('There are no time entries available for this project to generate invoice items from.') }}
                                        </p>
                                        <div class="d-flex justify-content-center gap-2">
                                            <a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" class="btn btn-secondary">
                                                <i class="fas fa-arrow-left me-1"></i> {{ _('Back to Invoice') }}
                                            </a>
                                            <a href="{{ url_for('timer.manual_entry') }}" class="btn btn-primary">
                                                <i class="fas fa-plus me-1"></i> {{ _('Add Time Entry') }}
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <!-- Quick Actions Card -->
                    <div class="card shadow-sm border-0 mb-3">
                        <div class="card-header bg-light py-3">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-bolt me-2"></i>{{ _('Quick Actions') }}
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-outline-primary" onclick="selectRecentEntries()">
                                    <i class="fas fa-calendar-week me-2"></i> {{ _('Last 7 Days') }}
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="selectThisMonth()">
                                    <i class="fas fa-calendar-alt me-2"></i> {{ _('This Month') }}
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="selectHighValueEntries()">
                                    <i class="fas fa-star me-2"></i> {{ _('High Value Tasks') }}
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="clearSelection()">
                                    <i class="fas fa-times me-2"></i> {{ _('Clear Selection') }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Tips Card -->
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-light py-3">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-lightbulb me-2"></i>{{ _('Tips') }}
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="tip-item mb-3">
                                <div class="tip-icon text-info">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="tip-content">
                                    <strong>{{ _('Smart Selection') }}</strong>
                                    <p class="small text-muted mb-0">
                                        {{ _('Use quick actions to select time entries by date ranges or task types') }}
                                    </p>
                                </div>
                            </div>
                            
                            <div class="tip-item mb-3">
                                <div class="tip-icon text-success">
                                    <i class="fas fa-calculator"></i>
                                </div>
                                <div class="tip-content">
                                    <strong>{{ _('Automatic Calculation') }}</strong>
                                    <p class="small text-muted mb-0">
                                        {{ _("Line items are automatically calculated using the project's hourly rate") }}
                                    </p>
                                </div>
                            </div>
                            
                            <div class="tip-item">
                                <div class="tip-icon text-warning">
                                    <i class="fas fa-edit"></i>
                                </div>
                                <div class="tip-content">
                                    <strong>{{ _('Review & Edit') }}</strong>
                                    <p class="small text-muted mb-0">
                                        {{ _('You can edit generated items before finalizing the invoice') }}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.summary-item {
    text-align: center;
    padding: 16px;
}

.summary-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 8px;
}

.summary-value {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
}

.selection-controls {
    background: var(--light-color);
    padding: 16px;
    border-radius: 8px;
    border: 1px solid var(--border-color);
}

.selection-summary .badge {
    font-size: 14px;
    padding: 8px 12px;
}

.time-entry-row {
    transition: all 0.2s ease;
}

.time-entry-row:hover {
    background-color: var(--light-color);
}

.time-entry-row.selected {
    background-color: rgba(59, 130, 246, 0.1);
    border-left: 4px solid var(--primary-color);
}

.date-info .date-value {
    font-weight: 600;
    color: var(--text-primary);
}

.user-info .user-name {
    font-weight: 600;
    color: var(--text-primary);
}

.task-badge {
    background: var(--info-color);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
}

.project-badge {
    background: var(--secondary-color);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
}

.duration-badge {
    background: var(--primary-color);
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
}

.notes-content .notes-text {
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 4px;
}

.tip-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.tip-icon {
    font-size: 18px;
    margin-top: 2px;
}

.tip-content strong {
    display: block;
    font-size: 14px;
    margin-bottom: 4px;
}

.empty-state {
    padding: 2rem;
}

.empty-state i {
    opacity: 0.5;
}

@media (max-width: 768px) {
    .selection-controls {
        flex-direction: column;
        gap: 16px;
    }
    
    .selection-summary {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }
    
    .table-responsive {
        font-size: 14px;
    }
    
    .btn-group {
        flex-direction: column;
        width: 100%;
    }
    
    .btn-group .btn {
        margin-bottom: 8px;
        border-radius: 6px !important;
    }
}
</style>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize selection summary
    updateSelectionSummary();

    // Hover effects
    document.querySelectorAll('.time-entry-row').forEach(row => {
        row.addEventListener('mouseenter', () => row.classList.add('table-active'));
        row.addEventListener('mouseleave', () => row.classList.remove('table-active'));
    });

    // Checkbox change handlers
    document.querySelectorAll('.time-entry-checkbox').forEach(cb => {
        cb.addEventListener('change', function() {
            updateRowSelection(this);
            updateSelectionSummary();
        });
    });

    // Form validation
    const form = document.getElementById('timeEntriesForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.time-entry-checkbox:checked').length;
            if (selectedCount === 0) {
                e.preventDefault();
                showAlert('{{ _('Please select at least one time entry to generate invoice items.') }}', 'warning');
            }
        });
    }
});

function toggleAllEntries() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.time-entry-checkbox');
    const rows = document.querySelectorAll('.time-entry-row');
    const checked = !!selectAll.checked;

    checkboxes.forEach(cb => { cb.checked = checked; });
    rows.forEach(row => { row.classList.toggle('selected', checked); });
    updateSelectionSummary();
}

function updateRowSelection(checkbox) {
    const row = checkbox.closest('.time-entry-row');
    if (row) {
        row.classList.toggle('selected', checkbox.checked);
    }
}

function updateSelectionSummary() {
    const selectedCheckboxes = document.querySelectorAll('.time-entry-checkbox:checked');
    const selectedCount = selectedCheckboxes.length;
    let totalHours = 0;
    selectedCheckboxes.forEach(cb => {
        totalHours += parseFloat(cb.getAttribute('data-duration') || '0');
    });

    const setText = (id, text) => { const el = document.getElementById(id); if (el) el.textContent = text; };
    setText('selectedCount', selectedCount);
    setText('totalHours', totalHours.toFixed(2));
    setText('selectedCountText', selectedCount);
    setText('totalHoursText', totalHours.toFixed(2));

    const generateBtn = document.getElementById('generateBtn');
    if (generateBtn) generateBtn.disabled = selectedCount === 0;
}

function selectRecentEntries() {
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    const currentYear = new Date().getFullYear();

    document.querySelectorAll('.time-entry-checkbox').forEach(cb => {
        const row = cb.closest('.time-entry-row');
        const dateTextEl = row.querySelector('.date-value');
        const dateText = dateTextEl ? dateTextEl.textContent : '';
        const date = new Date(`${dateText} ${currentYear}`);
        if (!isNaN(date.getTime()) && date >= sevenDaysAgo) {
            cb.checked = true;
            row.classList.add('selected');
        }
    });

    const selectAll = document.getElementById('selectAll');
    if (selectAll) selectAll.checked = false;
    updateSelectionSummary();
}

function selectThisMonth() {
    const now = new Date();
    const currentMonth = now.getMonth();
    const currentYear = now.getFullYear();

    document.querySelectorAll('.time-entry-checkbox').forEach(cb => {
        const row = cb.closest('.time-entry-row');
        const dateText = row.querySelector('.date-value')?.textContent || '';
        const date = new Date(`${dateText} ${currentYear}`);
        if (!isNaN(date.getTime()) && date.getMonth() === currentMonth && date.getFullYear() === currentYear) {
            cb.checked = true;
            row.classList.add('selected');
        }
    });

    const selectAll = document.getElementById('selectAll');
    if (selectAll) selectAll.checked = false;
    updateSelectionSummary();
}

function selectHighValueEntries() {
    document.querySelectorAll('.time-entry-checkbox').forEach(cb => {
        const duration = parseFloat(cb.getAttribute('data-duration') || '0');
        if (duration > 2) {
            cb.checked = true;
            const row = cb.closest('.time-entry-row');
            if (row) row.classList.add('selected');
        }
    });
    const selectAll = document.getElementById('selectAll');
    if (selectAll) selectAll.checked = false;
    updateSelectionSummary();
}

function clearSelection() {
    document.querySelectorAll('.time-entry-checkbox').forEach(cb => { cb.checked = false; });
    document.querySelectorAll('.time-entry-row').forEach(row => row.classList.remove('selected'));
    const selectAll = document.getElementById('selectAll');
    if (selectAll) selectAll.checked = false;
    updateSelectionSummary();
}

function showAlert(message, type) {
    const container = document.querySelector('.container-fluid');
    if (!container) return;
    const wrapper = document.createElement('div');
    wrapper.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>`;
    container.prepend(wrapper.firstElementChild);
    setTimeout(() => {
        const alert = container.querySelector('.alert');
        if (alert) alert.remove();
    }, 5000);
}
</script>
{% endblock %}
